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

Subversion Repositories openrisc

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

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

Line No. Rev Author Line
1 714 jeremybenn
// gogo.cc -- Go frontend parsed representation.
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 "go-c.h"
10
#include "go-dump.h"
11
#include "lex.h"
12
#include "types.h"
13
#include "statements.h"
14
#include "expressions.h"
15
#include "dataflow.h"
16
#include "runtime.h"
17
#include "import.h"
18
#include "export.h"
19
#include "backend.h"
20
#include "gogo.h"
21
 
22
// Class Gogo.
23
 
24
Gogo::Gogo(Backend* backend, Linemap* linemap, int int_type_size,
25
           int pointer_size)
26
  : backend_(backend),
27
    linemap_(linemap),
28
    package_(NULL),
29
    functions_(),
30
    globals_(new Bindings(NULL)),
31
    imports_(),
32
    imported_unsafe_(false),
33
    packages_(),
34
    init_functions_(),
35
    need_init_fn_(false),
36
    init_fn_name_(),
37
    imported_init_fns_(),
38
    unique_prefix_(),
39
    unique_prefix_specified_(false),
40
    verify_types_(),
41
    interface_types_(),
42
    specific_type_functions_(),
43
    specific_type_functions_are_written_(false),
44
    named_types_are_converted_(false)
45
{
46
  const Location loc = Linemap::predeclared_location();
47
 
48
  Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
49
                                                   RUNTIME_TYPE_KIND_UINT8);
50
  this->add_named_type(uint8_type);
51
  this->add_named_type(Type::make_integer_type("uint16", true,  16,
52
                                               RUNTIME_TYPE_KIND_UINT16));
53
  this->add_named_type(Type::make_integer_type("uint32", true,  32,
54
                                               RUNTIME_TYPE_KIND_UINT32));
55
  this->add_named_type(Type::make_integer_type("uint64", true,  64,
56
                                               RUNTIME_TYPE_KIND_UINT64));
57
 
58
  this->add_named_type(Type::make_integer_type("int8",  false,   8,
59
                                               RUNTIME_TYPE_KIND_INT8));
60
  this->add_named_type(Type::make_integer_type("int16", false,  16,
61
                                               RUNTIME_TYPE_KIND_INT16));
62
  Named_type* int32_type = Type::make_integer_type("int32", false,  32,
63
                                                   RUNTIME_TYPE_KIND_INT32);
64
  this->add_named_type(int32_type);
65
  this->add_named_type(Type::make_integer_type("int64", false,  64,
66
                                               RUNTIME_TYPE_KIND_INT64));
67
 
68
  this->add_named_type(Type::make_float_type("float32", 32,
69
                                             RUNTIME_TYPE_KIND_FLOAT32));
70
  this->add_named_type(Type::make_float_type("float64", 64,
71
                                             RUNTIME_TYPE_KIND_FLOAT64));
72
 
73
  this->add_named_type(Type::make_complex_type("complex64", 64,
74
                                               RUNTIME_TYPE_KIND_COMPLEX64));
75
  this->add_named_type(Type::make_complex_type("complex128", 128,
76
                                               RUNTIME_TYPE_KIND_COMPLEX128));
77
 
78
  if (int_type_size < 32)
79
    int_type_size = 32;
80
  this->add_named_type(Type::make_integer_type("uint", true,
81
                                               int_type_size,
82
                                               RUNTIME_TYPE_KIND_UINT));
83
  Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
84
                                                 RUNTIME_TYPE_KIND_INT);
85
  this->add_named_type(int_type);
86
 
87
  this->add_named_type(Type::make_integer_type("uintptr", true,
88
                                               pointer_size,
89
                                               RUNTIME_TYPE_KIND_UINTPTR));
90
 
91
  // "byte" is an alias for "uint8".
92
  uint8_type->integer_type()->set_is_byte();
93
  Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
94
                                                    loc);
95
  this->add_named_type(byte_type->type_value());
96
 
97
  // "rune" is an alias for "int32".
98
  int32_type->integer_type()->set_is_rune();
99
  Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
100
                                                    loc);
101
  this->add_named_type(rune_type->type_value());
102
 
103
  this->add_named_type(Type::make_named_bool_type());
104
 
105
  this->add_named_type(Type::make_named_string_type());
106
 
107
  // "error" is interface { Error() string }.
108
  {
109
    Typed_identifier_list *methods = new Typed_identifier_list;
110
    Typed_identifier_list *results = new Typed_identifier_list;
111
    results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
112
    Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
113
    methods->push_back(Typed_identifier("Error", method_type, loc));
114
    Interface_type *error_iface = Type::make_interface_type(methods, loc);
115
    error_iface->finalize_methods();
116
    Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
117
    this->add_named_type(error_type);
118
  }
119
 
120
  this->globals_->add_constant(Typed_identifier("true",
121
                                                Type::make_boolean_type(),
122
                                                loc),
123
                               NULL,
124
                               Expression::make_boolean(true, loc),
125
                               0);
126
  this->globals_->add_constant(Typed_identifier("false",
127
                                                Type::make_boolean_type(),
128
                                                loc),
129
                               NULL,
130
                               Expression::make_boolean(false, loc),
131
                               0);
132
 
133
  this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
134
                                                loc),
135
                               NULL,
136
                               Expression::make_nil(loc),
137
                               0);
138
 
139
  Type* abstract_int_type = Type::make_abstract_integer_type();
140
  this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
141
                                                loc),
142
                               NULL,
143
                               Expression::make_iota(),
144
                               0);
145
 
146
  Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
147
  new_type->set_is_varargs();
148
  new_type->set_is_builtin();
149
  this->globals_->add_function_declaration("new", NULL, new_type, loc);
150
 
151
  Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
152
  make_type->set_is_varargs();
153
  make_type->set_is_builtin();
154
  this->globals_->add_function_declaration("make", NULL, make_type, loc);
155
 
156
  Typed_identifier_list* len_result = new Typed_identifier_list();
157
  len_result->push_back(Typed_identifier("", int_type, loc));
158
  Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
159
                                                     loc);
160
  len_type->set_is_builtin();
161
  this->globals_->add_function_declaration("len", NULL, len_type, loc);
162
 
163
  Typed_identifier_list* cap_result = new Typed_identifier_list();
164
  cap_result->push_back(Typed_identifier("", int_type, loc));
165
  Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
166
                                                     loc);
167
  cap_type->set_is_builtin();
168
  this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
169
 
170
  Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
171
  print_type->set_is_varargs();
172
  print_type->set_is_builtin();
173
  this->globals_->add_function_declaration("print", NULL, print_type, loc);
174
 
175
  print_type = Type::make_function_type(NULL, NULL, NULL, loc);
176
  print_type->set_is_varargs();
177
  print_type->set_is_builtin();
178
  this->globals_->add_function_declaration("println", NULL, print_type, loc);
179
 
180
  Type *empty = Type::make_empty_interface_type(loc);
181
  Typed_identifier_list* panic_parms = new Typed_identifier_list();
182
  panic_parms->push_back(Typed_identifier("e", empty, loc));
183
  Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
184
                                                       NULL, loc);
185
  panic_type->set_is_builtin();
186
  this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
187
 
188
  Typed_identifier_list* recover_result = new Typed_identifier_list();
189
  recover_result->push_back(Typed_identifier("", empty, loc));
190
  Function_type* recover_type = Type::make_function_type(NULL, NULL,
191
                                                         recover_result,
192
                                                         loc);
193
  recover_type->set_is_builtin();
194
  this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
195
 
196
  Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
197
  close_type->set_is_varargs();
198
  close_type->set_is_builtin();
199
  this->globals_->add_function_declaration("close", NULL, close_type, loc);
200
 
201
  Typed_identifier_list* copy_result = new Typed_identifier_list();
202
  copy_result->push_back(Typed_identifier("", int_type, loc));
203
  Function_type* copy_type = Type::make_function_type(NULL, NULL,
204
                                                      copy_result, loc);
205
  copy_type->set_is_varargs();
206
  copy_type->set_is_builtin();
207
  this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
208
 
209
  Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
210
  append_type->set_is_varargs();
211
  append_type->set_is_builtin();
212
  this->globals_->add_function_declaration("append", NULL, append_type, loc);
213
 
214
  Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
215
  complex_type->set_is_varargs();
216
  complex_type->set_is_builtin();
217
  this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
218
 
219
  Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
220
  real_type->set_is_varargs();
221
  real_type->set_is_builtin();
222
  this->globals_->add_function_declaration("real", NULL, real_type, loc);
223
 
224
  Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
225
  imag_type->set_is_varargs();
226
  imag_type->set_is_builtin();
227
  this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
228
 
229
  Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
230
  delete_type->set_is_varargs();
231
  delete_type->set_is_builtin();
232
  this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
233
}
234
 
235
// Munge name for use in an error message.
236
 
237
std::string
238
Gogo::message_name(const std::string& name)
239
{
240
  return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
241
}
242
 
243
// Get the package name.
244
 
245
const std::string&
246
Gogo::package_name() const
247
{
248
  go_assert(this->package_ != NULL);
249
  return this->package_->name();
250
}
251
 
252
// Set the package name.
253
 
254
void
255
Gogo::set_package_name(const std::string& package_name,
256
                       Location location)
257
{
258
  if (this->package_ != NULL && this->package_->name() != package_name)
259
    {
260
      error_at(location, "expected package %<%s%>",
261
               Gogo::message_name(this->package_->name()).c_str());
262
      return;
263
    }
264
 
265
  // If the user did not specify a unique prefix, we always use "go".
266
  // This in effect requires that the package name be unique.
267
  if (this->unique_prefix_.empty())
268
    this->unique_prefix_ = "go";
269
 
270
  this->package_ = this->register_package(package_name, this->unique_prefix_,
271
                                          location);
272
 
273
  // We used to permit people to qualify symbols with the current
274
  // package name (e.g., P.x), but we no longer do.
275
  // this->globals_->add_package(package_name, this->package_);
276
 
277
  if (this->is_main_package())
278
    {
279
      // Declare "main" as a function which takes no parameters and
280
      // returns no value.
281
      Location uloc = Linemap::unknown_location();
282
      this->declare_function("main",
283
                             Type::make_function_type (NULL, NULL, NULL, uloc),
284
                             uloc);
285
    }
286
}
287
 
288
// Return whether this is the "main" package.  This is not true if
289
// -fgo-prefix was used.
290
 
291
bool
292
Gogo::is_main_package() const
293
{
294
  return this->package_name() == "main" && !this->unique_prefix_specified_;
295
}
296
 
297
// Import a package.
298
 
299
void
300
Gogo::import_package(const std::string& filename,
301
                     const std::string& local_name,
302
                     bool is_local_name_exported,
303
                     Location location)
304
{
305
  if (filename == "unsafe")
306
    {
307
      this->import_unsafe(local_name, is_local_name_exported, location);
308
      return;
309
    }
310
 
311
  Imports::const_iterator p = this->imports_.find(filename);
312
  if (p != this->imports_.end())
313
    {
314
      Package* package = p->second;
315
      package->set_location(location);
316
      package->set_is_imported();
317
      std::string ln = local_name;
318
      bool is_ln_exported = is_local_name_exported;
319
      if (ln.empty())
320
        {
321
          ln = package->name();
322
          is_ln_exported = Lex::is_exported_name(ln);
323
        }
324
      if (ln == ".")
325
        {
326
          Bindings* bindings = package->bindings();
327
          for (Bindings::const_declarations_iterator p =
328
                 bindings->begin_declarations();
329
               p != bindings->end_declarations();
330
               ++p)
331
            this->add_named_object(p->second);
332
        }
333
      else if (ln == "_")
334
        package->set_uses_sink_alias();
335
      else
336
        {
337
          ln = this->pack_hidden_name(ln, is_ln_exported);
338
          this->package_->bindings()->add_package(ln, package);
339
        }
340
      return;
341
    }
342
 
343
  Import::Stream* stream = Import::open_package(filename, location);
344
  if (stream == NULL)
345
    {
346
      error_at(location, "import file %qs not found", filename.c_str());
347
      return;
348
    }
349
 
350
  Import imp(stream, location);
351
  imp.register_builtin_types(this);
352
  Package* package = imp.import(this, local_name, is_local_name_exported);
353
  if (package != NULL)
354
    {
355
      if (package->name() == this->package_name()
356
          && package->unique_prefix() == this->unique_prefix())
357
        error_at(location,
358
                 ("imported package uses same package name and prefix "
359
                  "as package being compiled (see -fgo-prefix option)"));
360
 
361
      this->imports_.insert(std::make_pair(filename, package));
362
      package->set_is_imported();
363
    }
364
 
365
  delete stream;
366
}
367
 
368
// Add an import control function for an imported package to the list.
369
 
370
void
371
Gogo::add_import_init_fn(const std::string& package_name,
372
                         const std::string& init_name, int prio)
373
{
374
  for (std::set<Import_init>::const_iterator p =
375
         this->imported_init_fns_.begin();
376
       p != this->imported_init_fns_.end();
377
       ++p)
378
    {
379
      if (p->init_name() == init_name
380
          && (p->package_name() != package_name || p->priority() != prio))
381
        {
382
          error("duplicate package initialization name %qs",
383
                Gogo::message_name(init_name).c_str());
384
          inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
385
                 Gogo::message_name(p->package_name()).c_str(),
386
                 p->priority());
387
          inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
388
                 Gogo::message_name(package_name).c_str(), prio);
389
          return;
390
        }
391
    }
392
 
393
  this->imported_init_fns_.insert(Import_init(package_name, init_name,
394
                                              prio));
395
}
396
 
397
// Return whether we are at the global binding level.
398
 
399
bool
400
Gogo::in_global_scope() const
401
{
402
  return this->functions_.empty();
403
}
404
 
405
// Return the current binding contour.
406
 
407
Bindings*
408
Gogo::current_bindings()
409
{
410
  if (!this->functions_.empty())
411
    return this->functions_.back().blocks.back()->bindings();
412
  else if (this->package_ != NULL)
413
    return this->package_->bindings();
414
  else
415
    return this->globals_;
416
}
417
 
418
const Bindings*
419
Gogo::current_bindings() const
420
{
421
  if (!this->functions_.empty())
422
    return this->functions_.back().blocks.back()->bindings();
423
  else if (this->package_ != NULL)
424
    return this->package_->bindings();
425
  else
426
    return this->globals_;
427
}
428
 
429
// Return the current block.
430
 
431
Block*
432
Gogo::current_block()
433
{
434
  if (this->functions_.empty())
435
    return NULL;
436
  else
437
    return this->functions_.back().blocks.back();
438
}
439
 
440
// Look up a name in the current binding contour.  If PFUNCTION is not
441
// NULL, set it to the function in which the name is defined, or NULL
442
// if the name is defined in global scope.
443
 
444
Named_object*
445
Gogo::lookup(const std::string& name, Named_object** pfunction) const
446
{
447
  if (pfunction != NULL)
448
    *pfunction = NULL;
449
 
450
  if (Gogo::is_sink_name(name))
451
    return Named_object::make_sink();
452
 
453
  for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
454
       p != this->functions_.rend();
455
       ++p)
456
    {
457
      Named_object* ret = p->blocks.back()->bindings()->lookup(name);
458
      if (ret != NULL)
459
        {
460
          if (pfunction != NULL)
461
            *pfunction = p->function;
462
          return ret;
463
        }
464
    }
465
 
466
  if (this->package_ != NULL)
467
    {
468
      Named_object* ret = this->package_->bindings()->lookup(name);
469
      if (ret != NULL)
470
        {
471
          if (ret->package() != NULL)
472
            ret->package()->set_used();
473
          return ret;
474
        }
475
    }
476
 
477
  // We do not look in the global namespace.  If we did, the global
478
  // namespace would effectively hide names which were defined in
479
  // package scope which we have not yet seen.  Instead,
480
  // define_global_names is called after parsing is over to connect
481
  // undefined names at package scope with names defined at global
482
  // scope.
483
 
484
  return NULL;
485
}
486
 
487
// Look up a name in the current block, without searching enclosing
488
// blocks.
489
 
490
Named_object*
491
Gogo::lookup_in_block(const std::string& name) const
492
{
493
  go_assert(!this->functions_.empty());
494
  go_assert(!this->functions_.back().blocks.empty());
495
  return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
496
}
497
 
498
// Look up a name in the global namespace.
499
 
500
Named_object*
501
Gogo::lookup_global(const char* name) const
502
{
503
  return this->globals_->lookup(name);
504
}
505
 
506
// Add an imported package.
507
 
508
Package*
509
Gogo::add_imported_package(const std::string& real_name,
510
                           const std::string& alias_arg,
511
                           bool is_alias_exported,
512
                           const std::string& unique_prefix,
513
                           Location location,
514
                           bool* padd_to_globals)
515
{
516
  // FIXME: Now that we compile packages as a whole, should we permit
517
  // importing the current package?
518
  if (this->package_name() == real_name
519
      && this->unique_prefix() == unique_prefix)
520
    {
521
      *padd_to_globals = false;
522
      if (!alias_arg.empty() && alias_arg != ".")
523
        {
524
          std::string alias = this->pack_hidden_name(alias_arg,
525
                                                     is_alias_exported);
526
          this->package_->bindings()->add_package(alias, this->package_);
527
        }
528
      return this->package_;
529
    }
530
  else if (alias_arg == ".")
531
    {
532
      *padd_to_globals = true;
533
      return this->register_package(real_name, unique_prefix, location);
534
    }
535
  else if (alias_arg == "_")
536
    {
537
      Package* ret = this->register_package(real_name, unique_prefix, location);
538
      ret->set_uses_sink_alias();
539
      return ret;
540
    }
541
  else
542
    {
543
      *padd_to_globals = false;
544
      std::string alias = alias_arg;
545
      if (alias.empty())
546
        {
547
          alias = real_name;
548
          is_alias_exported = Lex::is_exported_name(alias);
549
        }
550
      alias = this->pack_hidden_name(alias, is_alias_exported);
551
      Named_object* no = this->add_package(real_name, alias, unique_prefix,
552
                                           location);
553
      if (!no->is_package())
554
        return NULL;
555
      return no->package_value();
556
    }
557
}
558
 
559
// Add a package.
560
 
561
Named_object*
562
Gogo::add_package(const std::string& real_name, const std::string& alias,
563
                  const std::string& unique_prefix, Location location)
564
{
565
  go_assert(this->in_global_scope());
566
 
567
  // Register the package.  Note that we might have already seen it in
568
  // an earlier import.
569
  Package* package = this->register_package(real_name, unique_prefix, location);
570
 
571
  return this->package_->bindings()->add_package(alias, package);
572
}
573
 
574
// Register a package.  This package may or may not be imported.  This
575
// returns the Package structure for the package, creating if it
576
// necessary.
577
 
578
Package*
579
Gogo::register_package(const std::string& package_name,
580
                       const std::string& unique_prefix,
581
                       Location location)
582
{
583
  go_assert(!unique_prefix.empty() && !package_name.empty());
584
  std::string name = unique_prefix + '.' + package_name;
585
  Package* package = NULL;
586
  std::pair<Packages::iterator, bool> ins =
587
    this->packages_.insert(std::make_pair(name, package));
588
  if (!ins.second)
589
    {
590
      // We have seen this package name before.
591
      package = ins.first->second;
592
      go_assert(package != NULL);
593
      go_assert(package->name() == package_name
594
                 && package->unique_prefix() == unique_prefix);
595
      if (Linemap::is_unknown_location(package->location()))
596
        package->set_location(location);
597
    }
598
  else
599
    {
600
      // First time we have seen this package name.
601
      package = new Package(package_name, unique_prefix, location);
602
      go_assert(ins.first->second == NULL);
603
      ins.first->second = package;
604
    }
605
 
606
  return package;
607
}
608
 
609
// Start compiling a function.
610
 
611
Named_object*
612
Gogo::start_function(const std::string& name, Function_type* type,
613
                     bool add_method_to_type, Location location)
614
{
615
  bool at_top_level = this->functions_.empty();
616
 
617
  Block* block = new Block(NULL, location);
618
 
619
  Function* enclosing = (at_top_level
620
                         ? NULL
621
                         : this->functions_.back().function->func_value());
622
 
623
  Function* function = new Function(type, enclosing, block, location);
624
 
625
  if (type->is_method())
626
    {
627
      const Typed_identifier* receiver = type->receiver();
628
      Variable* this_param = new Variable(receiver->type(), NULL, false,
629
                                          true, true, location);
630
      std::string rname = receiver->name();
631
      if (rname.empty())
632
        {
633
          // We need to give receivers a name since they wind up in
634
          // DECL_ARGUMENTS.  FIXME.
635
          static unsigned int count;
636
          char buf[50];
637
          snprintf(buf, sizeof buf, "r.%u", count);
638
          ++count;
639
          rname = buf;
640
        }
641
      if (!Gogo::is_sink_name(rname))
642
        block->bindings()->add_variable(rname, NULL, this_param);
643
    }
644
 
645
  const Typed_identifier_list* parameters = type->parameters();
646
  bool is_varargs = type->is_varargs();
647
  if (parameters != NULL)
648
    {
649
      for (Typed_identifier_list::const_iterator p = parameters->begin();
650
           p != parameters->end();
651
           ++p)
652
        {
653
          Variable* param = new Variable(p->type(), NULL, false, true, false,
654
                                         location);
655
          if (is_varargs && p + 1 == parameters->end())
656
            param->set_is_varargs_parameter();
657
 
658
          std::string pname = p->name();
659
          if (pname.empty() || Gogo::is_sink_name(pname))
660
            {
661
              // We need to give parameters a name since they wind up
662
              // in DECL_ARGUMENTS.  FIXME.
663
              static unsigned int count;
664
              char buf[50];
665
              snprintf(buf, sizeof buf, "p.%u", count);
666
              ++count;
667
              pname = buf;
668
            }
669
          block->bindings()->add_variable(pname, NULL, param);
670
        }
671
    }
672
 
673
  function->create_result_variables(this);
674
 
675
  const std::string* pname;
676
  std::string nested_name;
677
  bool is_init = false;
678
  if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
679
    {
680
      if ((type->parameters() != NULL && !type->parameters()->empty())
681
          || (type->results() != NULL && !type->results()->empty()))
682
        error_at(location,
683
                 "func init must have no arguments and no return values");
684
      // There can be multiple "init" functions, so give them each a
685
      // different name.
686
      static int init_count;
687
      char buf[30];
688
      snprintf(buf, sizeof buf, ".$init%d", init_count);
689
      ++init_count;
690
      nested_name = buf;
691
      pname = &nested_name;
692
      is_init = true;
693
    }
694
  else if (!name.empty())
695
    pname = &name;
696
  else
697
    {
698
      // Invent a name for a nested function.
699
      static int nested_count;
700
      char buf[30];
701
      snprintf(buf, sizeof buf, ".$nested%d", nested_count);
702
      ++nested_count;
703
      nested_name = buf;
704
      pname = &nested_name;
705
    }
706
 
707
  Named_object* ret;
708
  if (Gogo::is_sink_name(*pname))
709
    {
710
      static int sink_count;
711
      char buf[30];
712
      snprintf(buf, sizeof buf, ".$sink%d", sink_count);
713
      ++sink_count;
714
      ret = Named_object::make_function(buf, NULL, function);
715
    }
716
  else if (!type->is_method())
717
    {
718
      ret = this->package_->bindings()->add_function(*pname, NULL, function);
719
      if (!ret->is_function() || ret->func_value() != function)
720
        {
721
          // Redefinition error.  Invent a name to avoid knockon
722
          // errors.
723
          static int redefinition_count;
724
          char buf[30];
725
          snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
726
          ++redefinition_count;
727
          ret = this->package_->bindings()->add_function(buf, NULL, function);
728
        }
729
    }
730
  else
731
    {
732
      if (!add_method_to_type)
733
        ret = Named_object::make_function(name, NULL, function);
734
      else
735
        {
736
          go_assert(at_top_level);
737
          Type* rtype = type->receiver()->type();
738
 
739
          // We want to look through the pointer created by the
740
          // parser, without getting an error if the type is not yet
741
          // defined.
742
          if (rtype->classification() == Type::TYPE_POINTER)
743
            rtype = rtype->points_to();
744
 
745
          if (rtype->is_error_type())
746
            ret = Named_object::make_function(name, NULL, function);
747
          else if (rtype->named_type() != NULL)
748
            {
749
              ret = rtype->named_type()->add_method(name, function);
750
              if (!ret->is_function())
751
                {
752
                  // Redefinition error.
753
                  ret = Named_object::make_function(name, NULL, function);
754
                }
755
            }
756
          else if (rtype->forward_declaration_type() != NULL)
757
            {
758
              Named_object* type_no =
759
                rtype->forward_declaration_type()->named_object();
760
              if (type_no->is_unknown())
761
                {
762
                  // If we are seeing methods it really must be a
763
                  // type.  Declare it as such.  An alternative would
764
                  // be to support lists of methods for unknown
765
                  // expressions.  Either way the error messages if
766
                  // this is not a type are going to get confusing.
767
                  Named_object* declared =
768
                    this->declare_package_type(type_no->name(),
769
                                               type_no->location());
770
                  go_assert(declared
771
                             == type_no->unknown_value()->real_named_object());
772
                }
773
              ret = rtype->forward_declaration_type()->add_method(name,
774
                                                                  function);
775
            }
776
          else
777
            go_unreachable();
778
        }
779
      this->package_->bindings()->add_method(ret);
780
    }
781
 
782
  this->functions_.resize(this->functions_.size() + 1);
783
  Open_function& of(this->functions_.back());
784
  of.function = ret;
785
  of.blocks.push_back(block);
786
 
787
  if (is_init)
788
    {
789
      this->init_functions_.push_back(ret);
790
      this->need_init_fn_ = true;
791
    }
792
 
793
  return ret;
794
}
795
 
796
// Finish compiling a function.
797
 
798
void
799
Gogo::finish_function(Location location)
800
{
801
  this->finish_block(location);
802
  go_assert(this->functions_.back().blocks.empty());
803
  this->functions_.pop_back();
804
}
805
 
806
// Return the current function.
807
 
808
Named_object*
809
Gogo::current_function() const
810
{
811
  go_assert(!this->functions_.empty());
812
  return this->functions_.back().function;
813
}
814
 
815
// Start a new block.
816
 
817
void
818
Gogo::start_block(Location location)
819
{
820
  go_assert(!this->functions_.empty());
821
  Block* block = new Block(this->current_block(), location);
822
  this->functions_.back().blocks.push_back(block);
823
}
824
 
825
// Finish a block.
826
 
827
Block*
828
Gogo::finish_block(Location location)
829
{
830
  go_assert(!this->functions_.empty());
831
  go_assert(!this->functions_.back().blocks.empty());
832
  Block* block = this->functions_.back().blocks.back();
833
  this->functions_.back().blocks.pop_back();
834
  block->set_end_location(location);
835
  return block;
836
}
837
 
838
// Add an erroneous name.
839
 
840
Named_object*
841
Gogo::add_erroneous_name(const std::string& name)
842
{
843
  return this->package_->bindings()->add_erroneous_name(name);
844
}
845
 
846
// Add an unknown name.
847
 
848
Named_object*
849
Gogo::add_unknown_name(const std::string& name, Location location)
850
{
851
  return this->package_->bindings()->add_unknown_name(name, location);
852
}
853
 
854
// Declare a function.
855
 
856
Named_object*
857
Gogo::declare_function(const std::string& name, Function_type* type,
858
                       Location location)
859
{
860
  if (!type->is_method())
861
    return this->current_bindings()->add_function_declaration(name, NULL, type,
862
                                                              location);
863
  else
864
    {
865
      // We don't bother to add this to the list of global
866
      // declarations.
867
      Type* rtype = type->receiver()->type();
868
 
869
      // We want to look through the pointer created by the
870
      // parser, without getting an error if the type is not yet
871
      // defined.
872
      if (rtype->classification() == Type::TYPE_POINTER)
873
        rtype = rtype->points_to();
874
 
875
      if (rtype->is_error_type())
876
        return NULL;
877
      else if (rtype->named_type() != NULL)
878
        return rtype->named_type()->add_method_declaration(name, NULL, type,
879
                                                           location);
880
      else if (rtype->forward_declaration_type() != NULL)
881
        {
882
          Forward_declaration_type* ftype = rtype->forward_declaration_type();
883
          return ftype->add_method_declaration(name, NULL, type, location);
884
        }
885
      else
886
        go_unreachable();
887
    }
888
}
889
 
890
// Add a label definition.
891
 
892
Label*
893
Gogo::add_label_definition(const std::string& label_name,
894
                           Location location)
895
{
896
  go_assert(!this->functions_.empty());
897
  Function* func = this->functions_.back().function->func_value();
898
  Label* label = func->add_label_definition(this, label_name, location);
899
  this->add_statement(Statement::make_label_statement(label, location));
900
  return label;
901
}
902
 
903
// Add a label reference.
904
 
905
Label*
906
Gogo::add_label_reference(const std::string& label_name,
907
                          Location location, bool issue_goto_errors)
908
{
909
  go_assert(!this->functions_.empty());
910
  Function* func = this->functions_.back().function->func_value();
911
  return func->add_label_reference(this, label_name, location,
912
                                   issue_goto_errors);
913
}
914
 
915
// Return the current binding state.
916
 
917
Bindings_snapshot*
918
Gogo::bindings_snapshot(Location location)
919
{
920
  return new Bindings_snapshot(this->current_block(), location);
921
}
922
 
923
// Add a statement.
924
 
925
void
926
Gogo::add_statement(Statement* statement)
927
{
928
  go_assert(!this->functions_.empty()
929
             && !this->functions_.back().blocks.empty());
930
  this->functions_.back().blocks.back()->add_statement(statement);
931
}
932
 
933
// Add a block.
934
 
935
void
936
Gogo::add_block(Block* block, Location location)
937
{
938
  go_assert(!this->functions_.empty()
939
             && !this->functions_.back().blocks.empty());
940
  Statement* statement = Statement::make_block_statement(block, location);
941
  this->functions_.back().blocks.back()->add_statement(statement);
942
}
943
 
944
// Add a constant.
945
 
946
Named_object*
947
Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
948
                   int iota_value)
949
{
950
  return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
951
}
952
 
953
// Add a type.
954
 
955
void
956
Gogo::add_type(const std::string& name, Type* type, Location location)
957
{
958
  Named_object* no = this->current_bindings()->add_type(name, NULL, type,
959
                                                        location);
960
  if (!this->in_global_scope() && no->is_type())
961
    no->type_value()->set_in_function(this->functions_.back().function);
962
}
963
 
964
// Add a named type.
965
 
966
void
967
Gogo::add_named_type(Named_type* type)
968
{
969
  go_assert(this->in_global_scope());
970
  this->current_bindings()->add_named_type(type);
971
}
972
 
973
// Declare a type.
974
 
975
Named_object*
976
Gogo::declare_type(const std::string& name, Location location)
977
{
978
  Bindings* bindings = this->current_bindings();
979
  Named_object* no = bindings->add_type_declaration(name, NULL, location);
980
  if (!this->in_global_scope() && no->is_type_declaration())
981
    {
982
      Named_object* f = this->functions_.back().function;
983
      no->type_declaration_value()->set_in_function(f);
984
    }
985
  return no;
986
}
987
 
988
// Declare a type at the package level.
989
 
990
Named_object*
991
Gogo::declare_package_type(const std::string& name, Location location)
992
{
993
  return this->package_->bindings()->add_type_declaration(name, NULL, location);
994
}
995
 
996
// Declare a function at the package level.
997
 
998
Named_object*
999
Gogo::declare_package_function(const std::string& name, Function_type* type,
1000
                               Location location)
1001
{
1002
  return this->package_->bindings()->add_function_declaration(name, NULL, type,
1003
                                                              location);
1004
}
1005
 
1006
// Define a type which was already declared.
1007
 
1008
void
1009
Gogo::define_type(Named_object* no, Named_type* type)
1010
{
1011
  this->current_bindings()->define_type(no, type);
1012
}
1013
 
1014
// Add a variable.
1015
 
1016
Named_object*
1017
Gogo::add_variable(const std::string& name, Variable* variable)
1018
{
1019
  Named_object* no = this->current_bindings()->add_variable(name, NULL,
1020
                                                            variable);
1021
 
1022
  // In a function the middle-end wants to see a DECL_EXPR node.
1023
  if (no != NULL
1024
      && no->is_variable()
1025
      && !no->var_value()->is_parameter()
1026
      && !this->functions_.empty())
1027
    this->add_statement(Statement::make_variable_declaration(no));
1028
 
1029
  return no;
1030
}
1031
 
1032
// Add a sink--a reference to the blank identifier _.
1033
 
1034
Named_object*
1035
Gogo::add_sink()
1036
{
1037
  return Named_object::make_sink();
1038
}
1039
 
1040
// Add a named object.
1041
 
1042
void
1043
Gogo::add_named_object(Named_object* no)
1044
{
1045
  this->current_bindings()->add_named_object(no);
1046
}
1047
 
1048
// Mark all local variables used.  This is used when some types of
1049
// parse error occur.
1050
 
1051
void
1052
Gogo::mark_locals_used()
1053
{
1054
  for (Open_functions::iterator pf = this->functions_.begin();
1055
       pf != this->functions_.end();
1056
       ++pf)
1057
    {
1058
      for (std::vector<Block*>::iterator pb = pf->blocks.begin();
1059
           pb != pf->blocks.end();
1060
           ++pb)
1061
        (*pb)->bindings()->mark_locals_used();
1062
    }
1063
}
1064
 
1065
// Record that we've seen an interface type.
1066
 
1067
void
1068
Gogo::record_interface_type(Interface_type* itype)
1069
{
1070
  this->interface_types_.push_back(itype);
1071
}
1072
 
1073
// Return a name for a thunk object.
1074
 
1075
std::string
1076
Gogo::thunk_name()
1077
{
1078
  static int thunk_count;
1079
  char thunk_name[50];
1080
  snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1081
  ++thunk_count;
1082
  return thunk_name;
1083
}
1084
 
1085
// Return whether a function is a thunk.
1086
 
1087
bool
1088
Gogo::is_thunk(const Named_object* no)
1089
{
1090
  return no->name().compare(0, 6, "$thunk") == 0;
1091
}
1092
 
1093
// Define the global names.  We do this only after parsing all the
1094
// input files, because the program might define the global names
1095
// itself.
1096
 
1097
void
1098
Gogo::define_global_names()
1099
{
1100
  for (Bindings::const_declarations_iterator p =
1101
         this->globals_->begin_declarations();
1102
       p != this->globals_->end_declarations();
1103
       ++p)
1104
    {
1105
      Named_object* global_no = p->second;
1106
      std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1107
      Named_object* no = this->package_->bindings()->lookup(name);
1108
      if (no == NULL)
1109
        continue;
1110
      no = no->resolve();
1111
      if (no->is_type_declaration())
1112
        {
1113
          if (global_no->is_type())
1114
            {
1115
              if (no->type_declaration_value()->has_methods())
1116
                error_at(no->location(),
1117
                         "may not define methods for global type");
1118
              no->set_type_value(global_no->type_value());
1119
            }
1120
          else
1121
            {
1122
              error_at(no->location(), "expected type");
1123
              Type* errtype = Type::make_error_type();
1124
              Named_object* err =
1125
                Named_object::make_type("erroneous_type", NULL, errtype,
1126
                                        Linemap::predeclared_location());
1127
              no->set_type_value(err->type_value());
1128
            }
1129
        }
1130
      else if (no->is_unknown())
1131
        no->unknown_value()->set_real_named_object(global_no);
1132
    }
1133
}
1134
 
1135
// Clear out names in file scope.
1136
 
1137
void
1138
Gogo::clear_file_scope()
1139
{
1140
  this->package_->bindings()->clear_file_scope();
1141
 
1142
  // Warn about packages which were imported but not used.
1143
  for (Packages::iterator p = this->packages_.begin();
1144
       p != this->packages_.end();
1145
       ++p)
1146
    {
1147
      Package* package = p->second;
1148
      if (package != this->package_
1149
          && package->is_imported()
1150
          && !package->used()
1151
          && !package->uses_sink_alias()
1152
          && !saw_errors())
1153
        error_at(package->location(), "imported and not used: %s",
1154
                 Gogo::message_name(package->name()).c_str());
1155
      package->clear_is_imported();
1156
      package->clear_uses_sink_alias();
1157
      package->clear_used();
1158
    }
1159
}
1160
 
1161
// Queue up a type specific function for later writing.  These are
1162
// written out in write_specific_type_functions, called after the
1163
// parse tree is lowered.
1164
 
1165
void
1166
Gogo::queue_specific_type_function(Type* type, Named_type* name,
1167
                                   const std::string& hash_name,
1168
                                   Function_type* hash_fntype,
1169
                                   const std::string& equal_name,
1170
                                   Function_type* equal_fntype)
1171
{
1172
  go_assert(!this->specific_type_functions_are_written_);
1173
  go_assert(!this->in_global_scope());
1174
  Specific_type_function* tsf = new Specific_type_function(type, name,
1175
                                                           hash_name,
1176
                                                           hash_fntype,
1177
                                                           equal_name,
1178
                                                           equal_fntype);
1179
  this->specific_type_functions_.push_back(tsf);
1180
}
1181
 
1182
// Look for types which need specific hash or equality functions.
1183
 
1184
class Specific_type_functions : public Traverse
1185
{
1186
 public:
1187
  Specific_type_functions(Gogo* gogo)
1188
    : Traverse(traverse_types),
1189
      gogo_(gogo)
1190
  { }
1191
 
1192
  int
1193
  type(Type*);
1194
 
1195
 private:
1196
  Gogo* gogo_;
1197
};
1198
 
1199
int
1200
Specific_type_functions::type(Type* t)
1201
{
1202
  Named_object* hash_fn;
1203
  Named_object* equal_fn;
1204
  switch (t->classification())
1205
    {
1206
    case Type::TYPE_NAMED:
1207
      {
1208
        Named_type* nt = t->named_type();
1209
        if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1210
          t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
1211
 
1212
        // If this is a struct type, we don't want to make functions
1213
        // for the unnamed struct.
1214
        Type* rt = nt->real_type();
1215
        if (rt->struct_type() == NULL)
1216
          {
1217
            if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1218
              return TRAVERSE_EXIT;
1219
          }
1220
        else
1221
          {
1222
            // If this type is defined in another package, then we don't
1223
            // need to worry about the unexported fields.
1224
            bool is_defined_elsewhere = nt->named_object()->package() != NULL;
1225
            const Struct_field_list* fields = rt->struct_type()->fields();
1226
            for (Struct_field_list::const_iterator p = fields->begin();
1227
                 p != fields->end();
1228
                 ++p)
1229
              {
1230
                if (is_defined_elsewhere
1231
                    && Gogo::is_hidden_name(p->field_name()))
1232
                  continue;
1233
                if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
1234
                  return TRAVERSE_EXIT;
1235
              }
1236
          }
1237
 
1238
        return TRAVERSE_SKIP_COMPONENTS;
1239
      }
1240
 
1241
    case Type::TYPE_STRUCT:
1242
    case Type::TYPE_ARRAY:
1243
      if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1244
        t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1245
      break;
1246
 
1247
    default:
1248
      break;
1249
    }
1250
 
1251
  return TRAVERSE_CONTINUE;
1252
}
1253
 
1254
// Write out type specific functions.
1255
 
1256
void
1257
Gogo::write_specific_type_functions()
1258
{
1259
  Specific_type_functions stf(this);
1260
  this->traverse(&stf);
1261
 
1262
  while (!this->specific_type_functions_.empty())
1263
    {
1264
      Specific_type_function* tsf = this->specific_type_functions_.back();
1265
      this->specific_type_functions_.pop_back();
1266
      tsf->type->write_specific_type_functions(this, tsf->name,
1267
                                               tsf->hash_name,
1268
                                               tsf->hash_fntype,
1269
                                               tsf->equal_name,
1270
                                               tsf->equal_fntype);
1271
      delete tsf;
1272
    }
1273
  this->specific_type_functions_are_written_ = true;
1274
}
1275
 
1276
// Traverse the tree.
1277
 
1278
void
1279
Gogo::traverse(Traverse* traverse)
1280
{
1281
  // Traverse the current package first for consistency.  The other
1282
  // packages will only contain imported types, constants, and
1283
  // declarations.
1284
  if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1285
    return;
1286
  for (Packages::const_iterator p = this->packages_.begin();
1287
       p != this->packages_.end();
1288
       ++p)
1289
    {
1290
      if (p->second != this->package_)
1291
        {
1292
          if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1293
            break;
1294
        }
1295
    }
1296
}
1297
 
1298
// Add a type to verify.  This is used for types of sink variables, in
1299
// order to give appropriate error messages.
1300
 
1301
void
1302
Gogo::add_type_to_verify(Type* type)
1303
{
1304
  this->verify_types_.push_back(type);
1305
}
1306
 
1307
// Traversal class used to verify types.
1308
 
1309
class Verify_types : public Traverse
1310
{
1311
 public:
1312
  Verify_types()
1313
    : Traverse(traverse_types)
1314
  { }
1315
 
1316
  int
1317
  type(Type*);
1318
};
1319
 
1320
// Verify that a type is correct.
1321
 
1322
int
1323
Verify_types::type(Type* t)
1324
{
1325
  if (!t->verify())
1326
    return TRAVERSE_SKIP_COMPONENTS;
1327
  return TRAVERSE_CONTINUE;
1328
}
1329
 
1330
// Verify that all types are correct.
1331
 
1332
void
1333
Gogo::verify_types()
1334
{
1335
  Verify_types traverse;
1336
  this->traverse(&traverse);
1337
 
1338
  for (std::vector<Type*>::iterator p = this->verify_types_.begin();
1339
       p != this->verify_types_.end();
1340
       ++p)
1341
    (*p)->verify();
1342
  this->verify_types_.clear();
1343
}
1344
 
1345
// Traversal class used to lower parse tree.
1346
 
1347
class Lower_parse_tree : public Traverse
1348
{
1349
 public:
1350
  Lower_parse_tree(Gogo* gogo, Named_object* function)
1351
    : Traverse(traverse_variables
1352
               | traverse_constants
1353
               | traverse_functions
1354
               | traverse_statements
1355
               | traverse_expressions),
1356
      gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1357
  { }
1358
 
1359
  void
1360
  set_inserter(const Statement_inserter* inserter)
1361
  { this->inserter_ = *inserter; }
1362
 
1363
  int
1364
  variable(Named_object*);
1365
 
1366
  int
1367
  constant(Named_object*, bool);
1368
 
1369
  int
1370
  function(Named_object*);
1371
 
1372
  int
1373
  statement(Block*, size_t* pindex, Statement*);
1374
 
1375
  int
1376
  expression(Expression**);
1377
 
1378
 private:
1379
  // General IR.
1380
  Gogo* gogo_;
1381
  // The function we are traversing.
1382
  Named_object* function_;
1383
  // Value to use for the predeclared constant iota.
1384
  int iota_value_;
1385
  // Current statement inserter for use by expressions.
1386
  Statement_inserter inserter_;
1387
};
1388
 
1389
// Lower variables.
1390
 
1391
int
1392
Lower_parse_tree::variable(Named_object* no)
1393
{
1394
  if (!no->is_variable())
1395
    return TRAVERSE_CONTINUE;
1396
 
1397
  if (no->is_variable() && no->var_value()->is_global())
1398
    {
1399
      // Global variables can have loops in their initialization
1400
      // expressions.  This is handled in lower_init_expression.
1401
      no->var_value()->lower_init_expression(this->gogo_, this->function_,
1402
                                             &this->inserter_);
1403
      return TRAVERSE_CONTINUE;
1404
    }
1405
 
1406
  // This is a local variable.  We are going to return
1407
  // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1408
  // initialization expression when we reach the variable declaration
1409
  // statement.  However, that means that we need to traverse the type
1410
  // ourselves.
1411
  if (no->var_value()->has_type())
1412
    {
1413
      Type* type = no->var_value()->type();
1414
      if (type != NULL)
1415
        {
1416
          if (Type::traverse(type, this) == TRAVERSE_EXIT)
1417
            return TRAVERSE_EXIT;
1418
        }
1419
    }
1420
  go_assert(!no->var_value()->has_pre_init());
1421
 
1422
  return TRAVERSE_SKIP_COMPONENTS;
1423
}
1424
 
1425
// Lower constants.  We handle constants specially so that we can set
1426
// the right value for the predeclared constant iota.  This works in
1427
// conjunction with the way we lower Const_expression objects.
1428
 
1429
int
1430
Lower_parse_tree::constant(Named_object* no, bool)
1431
{
1432
  Named_constant* nc = no->const_value();
1433
 
1434
  // Don't get into trouble if the constant's initializer expression
1435
  // refers to the constant itself.
1436
  if (nc->lowering())
1437
    return TRAVERSE_CONTINUE;
1438
  nc->set_lowering();
1439
 
1440
  go_assert(this->iota_value_ == -1);
1441
  this->iota_value_ = nc->iota_value();
1442
  nc->traverse_expression(this);
1443
  this->iota_value_ = -1;
1444
 
1445
  nc->clear_lowering();
1446
 
1447
  // We will traverse the expression a second time, but that will be
1448
  // fast.
1449
 
1450
  return TRAVERSE_CONTINUE;
1451
}
1452
 
1453
// Lower function closure types.  Record the function while lowering
1454
// it, so that we can pass it down when lowering an expression.
1455
 
1456
int
1457
Lower_parse_tree::function(Named_object* no)
1458
{
1459
  no->func_value()->set_closure_type();
1460
 
1461
  go_assert(this->function_ == NULL);
1462
  this->function_ = no;
1463
  int t = no->func_value()->traverse(this);
1464
  this->function_ = NULL;
1465
 
1466
  if (t == TRAVERSE_EXIT)
1467
    return t;
1468
  return TRAVERSE_SKIP_COMPONENTS;
1469
}
1470
 
1471
// Lower statement parse trees.
1472
 
1473
int
1474
Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1475
{
1476
  // Because we explicitly traverse the statement's contents
1477
  // ourselves, we want to skip block statements here.  There is
1478
  // nothing to lower in a block statement.
1479
  if (sorig->is_block_statement())
1480
    return TRAVERSE_CONTINUE;
1481
 
1482
  Statement_inserter hold_inserter(this->inserter_);
1483
  this->inserter_ = Statement_inserter(block, pindex);
1484
 
1485
  // Lower the expressions first.
1486
  int t = sorig->traverse_contents(this);
1487
  if (t == TRAVERSE_EXIT)
1488
    {
1489
      this->inserter_ = hold_inserter;
1490
      return t;
1491
    }
1492
 
1493
  // Keep lowering until nothing changes.
1494
  Statement* s = sorig;
1495
  while (true)
1496
    {
1497
      Statement* snew = s->lower(this->gogo_, this->function_, block,
1498
                                 &this->inserter_);
1499
      if (snew == s)
1500
        break;
1501
      s = snew;
1502
      t = s->traverse_contents(this);
1503
      if (t == TRAVERSE_EXIT)
1504
        {
1505
          this->inserter_ = hold_inserter;
1506
          return t;
1507
        }
1508
    }
1509
 
1510
  if (s != sorig)
1511
    block->replace_statement(*pindex, s);
1512
 
1513
  this->inserter_ = hold_inserter;
1514
  return TRAVERSE_SKIP_COMPONENTS;
1515
}
1516
 
1517
// Lower expression parse trees.
1518
 
1519
int
1520
Lower_parse_tree::expression(Expression** pexpr)
1521
{
1522
  // We have to lower all subexpressions first, so that we can get
1523
  // their type if necessary.  This is awkward, because we don't have
1524
  // a postorder traversal pass.
1525
  if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1526
    return TRAVERSE_EXIT;
1527
  // Keep lowering until nothing changes.
1528
  while (true)
1529
    {
1530
      Expression* e = *pexpr;
1531
      Expression* enew = e->lower(this->gogo_, this->function_,
1532
                                  &this->inserter_, this->iota_value_);
1533
      if (enew == e)
1534
        break;
1535
      if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
1536
        return TRAVERSE_EXIT;
1537
      *pexpr = enew;
1538
    }
1539
  return TRAVERSE_SKIP_COMPONENTS;
1540
}
1541
 
1542
// Lower the parse tree.  This is called after the parse is complete,
1543
// when all names should be resolved.
1544
 
1545
void
1546
Gogo::lower_parse_tree()
1547
{
1548
  Lower_parse_tree lower_parse_tree(this, NULL);
1549
  this->traverse(&lower_parse_tree);
1550
}
1551
 
1552
// Lower a block.
1553
 
1554
void
1555
Gogo::lower_block(Named_object* function, Block* block)
1556
{
1557
  Lower_parse_tree lower_parse_tree(this, function);
1558
  block->traverse(&lower_parse_tree);
1559
}
1560
 
1561
// Lower an expression.  INSERTER may be NULL, in which case the
1562
// expression had better not need to create any temporaries.
1563
 
1564
void
1565
Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1566
                       Expression** pexpr)
1567
{
1568
  Lower_parse_tree lower_parse_tree(this, function);
1569
  if (inserter != NULL)
1570
    lower_parse_tree.set_inserter(inserter);
1571
  lower_parse_tree.expression(pexpr);
1572
}
1573
 
1574
// Lower a constant.  This is called when lowering a reference to a
1575
// constant.  We have to make sure that the constant has already been
1576
// lowered.
1577
 
1578
void
1579
Gogo::lower_constant(Named_object* no)
1580
{
1581
  go_assert(no->is_const());
1582
  Lower_parse_tree lower(this, NULL);
1583
  lower.constant(no, false);
1584
}
1585
 
1586
// Look for interface types to finalize methods of inherited
1587
// interfaces.
1588
 
1589
class Finalize_methods : public Traverse
1590
{
1591
 public:
1592
  Finalize_methods(Gogo* gogo)
1593
    : Traverse(traverse_types),
1594
      gogo_(gogo)
1595
  { }
1596
 
1597
  int
1598
  type(Type*);
1599
 
1600
 private:
1601
  Gogo* gogo_;
1602
};
1603
 
1604
// Finalize the methods of an interface type.
1605
 
1606
int
1607
Finalize_methods::type(Type* t)
1608
{
1609
  // Check the classification so that we don't finalize the methods
1610
  // twice for a named interface type.
1611
  switch (t->classification())
1612
    {
1613
    case Type::TYPE_INTERFACE:
1614
      t->interface_type()->finalize_methods();
1615
      break;
1616
 
1617
    case Type::TYPE_NAMED:
1618
      {
1619
        // We have to finalize the methods of the real type first.
1620
        // But if the real type is a struct type, then we only want to
1621
        // finalize the methods of the field types, not of the struct
1622
        // type itself.  We don't want to add methods to the struct,
1623
        // since it has a name.
1624
        Named_type* nt = t->named_type();
1625
        Type* rt = nt->real_type();
1626
        if (rt->classification() != Type::TYPE_STRUCT)
1627
          {
1628
            if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1629
              return TRAVERSE_EXIT;
1630
          }
1631
        else
1632
          {
1633
            if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1634
              return TRAVERSE_EXIT;
1635
          }
1636
 
1637
        nt->finalize_methods(this->gogo_);
1638
 
1639
        // If this type is defined in a different package, then finalize the
1640
        // types of all the methods, since we won't see them otherwise.
1641
        if (nt->named_object()->package() != NULL && nt->has_any_methods())
1642
          {
1643
            const Methods* methods = nt->methods();
1644
            for (Methods::const_iterator p = methods->begin();
1645
                 p != methods->end();
1646
                 ++p)
1647
              {
1648
                if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1649
                  return TRAVERSE_EXIT;
1650
              }
1651
          }
1652
 
1653
        return TRAVERSE_SKIP_COMPONENTS;
1654
      }
1655
 
1656
    case Type::TYPE_STRUCT:
1657
      t->struct_type()->finalize_methods(this->gogo_);
1658
      break;
1659
 
1660
    default:
1661
      break;
1662
    }
1663
 
1664
  return TRAVERSE_CONTINUE;
1665
}
1666
 
1667
// Finalize method lists and build stub methods for types.
1668
 
1669
void
1670
Gogo::finalize_methods()
1671
{
1672
  Finalize_methods finalize(this);
1673
  this->traverse(&finalize);
1674
}
1675
 
1676
// Set types for unspecified variables and constants.
1677
 
1678
void
1679
Gogo::determine_types()
1680
{
1681
  Bindings* bindings = this->current_bindings();
1682
  for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1683
       p != bindings->end_definitions();
1684
       ++p)
1685
    {
1686
      if ((*p)->is_function())
1687
        (*p)->func_value()->determine_types();
1688
      else if ((*p)->is_variable())
1689
        (*p)->var_value()->determine_type();
1690
      else if ((*p)->is_const())
1691
        (*p)->const_value()->determine_type();
1692
 
1693
      // See if a variable requires us to build an initialization
1694
      // function.  We know that we will see all global variables
1695
      // here.
1696
      if (!this->need_init_fn_ && (*p)->is_variable())
1697
        {
1698
          Variable* variable = (*p)->var_value();
1699
 
1700
          // If this is a global variable which requires runtime
1701
          // initialization, we need an initialization function.
1702
          if (!variable->is_global())
1703
            ;
1704
          else if (variable->init() == NULL)
1705
            ;
1706
          else if (variable->type()->interface_type() != NULL)
1707
            this->need_init_fn_ = true;
1708
          else if (variable->init()->is_constant())
1709
            ;
1710
          else if (!variable->init()->is_composite_literal())
1711
            this->need_init_fn_ = true;
1712
          else if (variable->init()->is_nonconstant_composite_literal())
1713
            this->need_init_fn_ = true;
1714
 
1715
          // If this is a global variable which holds a pointer value,
1716
          // then we need an initialization function to register it as a
1717
          // GC root.
1718
          if (variable->is_global() && variable->type()->has_pointer())
1719
            this->need_init_fn_ = true;
1720
        }
1721
    }
1722
 
1723
  // Determine the types of constants in packages.
1724
  for (Packages::const_iterator p = this->packages_.begin();
1725
       p != this->packages_.end();
1726
       ++p)
1727
    p->second->determine_types();
1728
}
1729
 
1730
// Traversal class used for type checking.
1731
 
1732
class Check_types_traverse : public Traverse
1733
{
1734
 public:
1735
  Check_types_traverse(Gogo* gogo)
1736
    : Traverse(traverse_variables
1737
               | traverse_constants
1738
               | traverse_functions
1739
               | traverse_statements
1740
               | traverse_expressions),
1741
      gogo_(gogo)
1742
  { }
1743
 
1744
  int
1745
  variable(Named_object*);
1746
 
1747
  int
1748
  constant(Named_object*, bool);
1749
 
1750
  int
1751
  function(Named_object*);
1752
 
1753
  int
1754
  statement(Block*, size_t* pindex, Statement*);
1755
 
1756
  int
1757
  expression(Expression**);
1758
 
1759
 private:
1760
  // General IR.
1761
  Gogo* gogo_;
1762
};
1763
 
1764
// Check that a variable initializer has the right type.
1765
 
1766
int
1767
Check_types_traverse::variable(Named_object* named_object)
1768
{
1769
  if (named_object->is_variable())
1770
    {
1771
      Variable* var = named_object->var_value();
1772
 
1773
      // Give error if variable type is not defined.
1774
      var->type()->base();
1775
 
1776
      Expression* init = var->init();
1777
      std::string reason;
1778
      if (init != NULL
1779
          && !Type::are_assignable(var->type(), init->type(), &reason))
1780
        {
1781
          if (reason.empty())
1782
            error_at(var->location(), "incompatible type in initialization");
1783
          else
1784
            error_at(var->location(),
1785
                     "incompatible type in initialization (%s)",
1786
                     reason.c_str());
1787
          var->clear_init();
1788
        }
1789
      else if (!var->is_used()
1790
               && !var->is_global()
1791
               && !var->is_parameter()
1792
               && !var->is_receiver()
1793
               && !var->type()->is_error()
1794
               && (init == NULL || !init->is_error_expression())
1795
               && !Lex::is_invalid_identifier(named_object->name()))
1796
        error_at(var->location(), "%qs declared and not used",
1797
                 named_object->message_name().c_str());
1798
    }
1799
  return TRAVERSE_CONTINUE;
1800
}
1801
 
1802
// Check that a constant initializer has the right type.
1803
 
1804
int
1805
Check_types_traverse::constant(Named_object* named_object, bool)
1806
{
1807
  Named_constant* constant = named_object->const_value();
1808
  Type* ctype = constant->type();
1809
  if (ctype->integer_type() == NULL
1810
      && ctype->float_type() == NULL
1811
      && ctype->complex_type() == NULL
1812
      && !ctype->is_boolean_type()
1813
      && !ctype->is_string_type())
1814
    {
1815
      if (ctype->is_nil_type())
1816
        error_at(constant->location(), "const initializer cannot be nil");
1817
      else if (!ctype->is_error())
1818
        error_at(constant->location(), "invalid constant type");
1819
      constant->set_error();
1820
    }
1821
  else if (!constant->expr()->is_constant())
1822
    {
1823
      error_at(constant->expr()->location(), "expression is not constant");
1824
      constant->set_error();
1825
    }
1826
  else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1827
                                 NULL))
1828
    {
1829
      error_at(constant->location(),
1830
               "initialization expression has wrong type");
1831
      constant->set_error();
1832
    }
1833
  return TRAVERSE_CONTINUE;
1834
}
1835
 
1836
// There are no types to check in a function, but this is where we
1837
// issue warnings about labels which are defined but not referenced.
1838
 
1839
int
1840
Check_types_traverse::function(Named_object* no)
1841
{
1842
  no->func_value()->check_labels();
1843
  return TRAVERSE_CONTINUE;
1844
}
1845
 
1846
// Check that types are valid in a statement.
1847
 
1848
int
1849
Check_types_traverse::statement(Block*, size_t*, Statement* s)
1850
{
1851
  s->check_types(this->gogo_);
1852
  return TRAVERSE_CONTINUE;
1853
}
1854
 
1855
// Check that types are valid in an expression.
1856
 
1857
int
1858
Check_types_traverse::expression(Expression** expr)
1859
{
1860
  (*expr)->check_types(this->gogo_);
1861
  return TRAVERSE_CONTINUE;
1862
}
1863
 
1864
// Check that types are valid.
1865
 
1866
void
1867
Gogo::check_types()
1868
{
1869
  Check_types_traverse traverse(this);
1870
  this->traverse(&traverse);
1871
}
1872
 
1873
// Check the types in a single block.
1874
 
1875
void
1876
Gogo::check_types_in_block(Block* block)
1877
{
1878
  Check_types_traverse traverse(this);
1879
  block->traverse(&traverse);
1880
}
1881
 
1882
// A traversal class used to find a single shortcut operator within an
1883
// expression.
1884
 
1885
class Find_shortcut : public Traverse
1886
{
1887
 public:
1888
  Find_shortcut()
1889
    : Traverse(traverse_blocks
1890
               | traverse_statements
1891
               | traverse_expressions),
1892
      found_(NULL)
1893
  { }
1894
 
1895
  // A pointer to the expression which was found, or NULL if none was
1896
  // found.
1897
  Expression**
1898
  found() const
1899
  { return this->found_; }
1900
 
1901
 protected:
1902
  int
1903
  block(Block*)
1904
  { return TRAVERSE_SKIP_COMPONENTS; }
1905
 
1906
  int
1907
  statement(Block*, size_t*, Statement*)
1908
  { return TRAVERSE_SKIP_COMPONENTS; }
1909
 
1910
  int
1911
  expression(Expression**);
1912
 
1913
 private:
1914
  Expression** found_;
1915
};
1916
 
1917
// Find a shortcut expression.
1918
 
1919
int
1920
Find_shortcut::expression(Expression** pexpr)
1921
{
1922
  Expression* expr = *pexpr;
1923
  Binary_expression* be = expr->binary_expression();
1924
  if (be == NULL)
1925
    return TRAVERSE_CONTINUE;
1926
  Operator op = be->op();
1927
  if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1928
    return TRAVERSE_CONTINUE;
1929
  go_assert(this->found_ == NULL);
1930
  this->found_ = pexpr;
1931
  return TRAVERSE_EXIT;
1932
}
1933
 
1934
// A traversal class used to turn shortcut operators into explicit if
1935
// statements.
1936
 
1937
class Shortcuts : public Traverse
1938
{
1939
 public:
1940
  Shortcuts(Gogo* gogo)
1941
    : Traverse(traverse_variables
1942
               | traverse_statements),
1943
      gogo_(gogo)
1944
  { }
1945
 
1946
 protected:
1947
  int
1948
  variable(Named_object*);
1949
 
1950
  int
1951
  statement(Block*, size_t*, Statement*);
1952
 
1953
 private:
1954
  // Convert a shortcut operator.
1955
  Statement*
1956
  convert_shortcut(Block* enclosing, Expression** pshortcut);
1957
 
1958
  // The IR.
1959
  Gogo* gogo_;
1960
};
1961
 
1962
// Remove shortcut operators in a single statement.
1963
 
1964
int
1965
Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1966
{
1967
  // FIXME: This approach doesn't work for switch statements, because
1968
  // we add the new statements before the whole switch when we need to
1969
  // instead add them just before the switch expression.  The right
1970
  // fix is probably to lower switch statements with nonconstant cases
1971
  // to a series of conditionals.
1972
  if (s->switch_statement() != NULL)
1973
    return TRAVERSE_CONTINUE;
1974
 
1975
  while (true)
1976
    {
1977
      Find_shortcut find_shortcut;
1978
 
1979
      // If S is a variable declaration, then ordinary traversal won't
1980
      // do anything.  We want to explicitly traverse the
1981
      // initialization expression if there is one.
1982
      Variable_declaration_statement* vds = s->variable_declaration_statement();
1983
      Expression* init = NULL;
1984
      if (vds == NULL)
1985
        s->traverse_contents(&find_shortcut);
1986
      else
1987
        {
1988
          init = vds->var()->var_value()->init();
1989
          if (init == NULL)
1990
            return TRAVERSE_CONTINUE;
1991
          init->traverse(&init, &find_shortcut);
1992
        }
1993
      Expression** pshortcut = find_shortcut.found();
1994
      if (pshortcut == NULL)
1995
        return TRAVERSE_CONTINUE;
1996
 
1997
      Statement* snew = this->convert_shortcut(block, pshortcut);
1998
      block->insert_statement_before(*pindex, snew);
1999
      ++*pindex;
2000
 
2001
      if (pshortcut == &init)
2002
        vds->var()->var_value()->set_init(init);
2003
    }
2004
}
2005
 
2006
// Remove shortcut operators in the initializer of a global variable.
2007
 
2008
int
2009
Shortcuts::variable(Named_object* no)
2010
{
2011
  if (no->is_result_variable())
2012
    return TRAVERSE_CONTINUE;
2013
  Variable* var = no->var_value();
2014
  Expression* init = var->init();
2015
  if (!var->is_global() || init == NULL)
2016
    return TRAVERSE_CONTINUE;
2017
 
2018
  while (true)
2019
    {
2020
      Find_shortcut find_shortcut;
2021
      init->traverse(&init, &find_shortcut);
2022
      Expression** pshortcut = find_shortcut.found();
2023
      if (pshortcut == NULL)
2024
        return TRAVERSE_CONTINUE;
2025
 
2026
      Statement* snew = this->convert_shortcut(NULL, pshortcut);
2027
      var->add_preinit_statement(this->gogo_, snew);
2028
      if (pshortcut == &init)
2029
        var->set_init(init);
2030
    }
2031
}
2032
 
2033
// Given an expression which uses a shortcut operator, return a
2034
// statement which implements it, and update *PSHORTCUT accordingly.
2035
 
2036
Statement*
2037
Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2038
{
2039
  Binary_expression* shortcut = (*pshortcut)->binary_expression();
2040
  Expression* left = shortcut->left();
2041
  Expression* right = shortcut->right();
2042
  Location loc = shortcut->location();
2043
 
2044
  Block* retblock = new Block(enclosing, loc);
2045
  retblock->set_end_location(loc);
2046
 
2047
  Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
2048
                                                      left, loc);
2049
  retblock->add_statement(ts);
2050
 
2051
  Block* block = new Block(retblock, loc);
2052
  block->set_end_location(loc);
2053
  Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2054
  Statement* assign = Statement::make_assignment(tmpref, right, loc);
2055
  block->add_statement(assign);
2056
 
2057
  Expression* cond = Expression::make_temporary_reference(ts, loc);
2058
  if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2059
    cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2060
 
2061
  Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2062
                                                         loc);
2063
  retblock->add_statement(if_statement);
2064
 
2065
  *pshortcut = Expression::make_temporary_reference(ts, loc);
2066
 
2067
  delete shortcut;
2068
 
2069
  // Now convert any shortcut operators in LEFT and RIGHT.
2070
  Shortcuts shortcuts(this->gogo_);
2071
  retblock->traverse(&shortcuts);
2072
 
2073
  return Statement::make_block_statement(retblock, loc);
2074
}
2075
 
2076
// Turn shortcut operators into explicit if statements.  Doing this
2077
// considerably simplifies the order of evaluation rules.
2078
 
2079
void
2080
Gogo::remove_shortcuts()
2081
{
2082
  Shortcuts shortcuts(this);
2083
  this->traverse(&shortcuts);
2084
}
2085
 
2086
// A traversal class which finds all the expressions which must be
2087
// evaluated in order within a statement or larger expression.  This
2088
// is used to implement the rules about order of evaluation.
2089
 
2090
class Find_eval_ordering : public Traverse
2091
{
2092
 private:
2093
  typedef std::vector<Expression**> Expression_pointers;
2094
 
2095
 public:
2096
  Find_eval_ordering()
2097
    : Traverse(traverse_blocks
2098
               | traverse_statements
2099
               | traverse_expressions),
2100
      exprs_()
2101
  { }
2102
 
2103
  size_t
2104
  size() const
2105
  { return this->exprs_.size(); }
2106
 
2107
  typedef Expression_pointers::const_iterator const_iterator;
2108
 
2109
  const_iterator
2110
  begin() const
2111
  { return this->exprs_.begin(); }
2112
 
2113
  const_iterator
2114
  end() const
2115
  { return this->exprs_.end(); }
2116
 
2117
 protected:
2118
  int
2119
  block(Block*)
2120
  { return TRAVERSE_SKIP_COMPONENTS; }
2121
 
2122
  int
2123
  statement(Block*, size_t*, Statement*)
2124
  { return TRAVERSE_SKIP_COMPONENTS; }
2125
 
2126
  int
2127
  expression(Expression**);
2128
 
2129
 private:
2130
  // A list of pointers to expressions with side-effects.
2131
  Expression_pointers exprs_;
2132
};
2133
 
2134
// If an expression must be evaluated in order, put it on the list.
2135
 
2136
int
2137
Find_eval_ordering::expression(Expression** expression_pointer)
2138
{
2139
  // We have to look at subexpressions before this one.
2140
  if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2141
    return TRAVERSE_EXIT;
2142
  if ((*expression_pointer)->must_eval_in_order())
2143
    this->exprs_.push_back(expression_pointer);
2144
  return TRAVERSE_SKIP_COMPONENTS;
2145
}
2146
 
2147
// A traversal class for ordering evaluations.
2148
 
2149
class Order_eval : public Traverse
2150
{
2151
 public:
2152
  Order_eval(Gogo* gogo)
2153
    : Traverse(traverse_variables
2154
               | traverse_statements),
2155
      gogo_(gogo)
2156
  { }
2157
 
2158
  int
2159
  variable(Named_object*);
2160
 
2161
  int
2162
  statement(Block*, size_t*, Statement*);
2163
 
2164
 private:
2165
  // The IR.
2166
  Gogo* gogo_;
2167
};
2168
 
2169
// Implement the order of evaluation rules for a statement.
2170
 
2171
int
2172
Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2173
{
2174
  // FIXME: This approach doesn't work for switch statements, because
2175
  // we add the new statements before the whole switch when we need to
2176
  // instead add them just before the switch expression.  The right
2177
  // fix is probably to lower switch statements with nonconstant cases
2178
  // to a series of conditionals.
2179
  if (s->switch_statement() != NULL)
2180
    return TRAVERSE_CONTINUE;
2181
 
2182
  Find_eval_ordering find_eval_ordering;
2183
 
2184
  // If S is a variable declaration, then ordinary traversal won't do
2185
  // anything.  We want to explicitly traverse the initialization
2186
  // expression if there is one.
2187
  Variable_declaration_statement* vds = s->variable_declaration_statement();
2188
  Expression* init = NULL;
2189
  Expression* orig_init = NULL;
2190
  if (vds == NULL)
2191
    s->traverse_contents(&find_eval_ordering);
2192
  else
2193
    {
2194
      init = vds->var()->var_value()->init();
2195
      if (init == NULL)
2196
        return TRAVERSE_CONTINUE;
2197
      orig_init = init;
2198
 
2199
      // It might seem that this could be
2200
      // init->traverse_subexpressions.  Unfortunately that can fail
2201
      // in a case like
2202
      //   var err os.Error
2203
      //   newvar, err := call(arg())
2204
      // Here newvar will have an init of call result 0 of
2205
      // call(arg()).  If we only traverse subexpressions, we will
2206
      // only find arg(), and we won't bother to move anything out.
2207
      // Then we get to the assignment to err, we will traverse the
2208
      // whole statement, and this time we will find both call() and
2209
      // arg(), and so we will move them out.  This will cause them to
2210
      // be put into temporary variables before the assignment to err
2211
      // but after the declaration of newvar.  To avoid that problem,
2212
      // we traverse the entire expression here.
2213
      Expression::traverse(&init, &find_eval_ordering);
2214
    }
2215
 
2216
  if (find_eval_ordering.size() <= 1)
2217
    {
2218
      // If there is only one expression with a side-effect, we can
2219
      // leave it in place.
2220
      return TRAVERSE_CONTINUE;
2221
    }
2222
 
2223
  bool is_thunk = s->thunk_statement() != NULL;
2224
  for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2225
       p != find_eval_ordering.end();
2226
       ++p)
2227
    {
2228
      Expression** pexpr = *p;
2229
 
2230
      // The last expression in a thunk will be the call passed to go
2231
      // or defer, which we must not evaluate early.
2232
      if (is_thunk && p + 1 == find_eval_ordering.end())
2233
        break;
2234
 
2235
      Location loc = (*pexpr)->location();
2236
      Statement* s;
2237
      if ((*pexpr)->call_expression() == NULL
2238
          || (*pexpr)->call_expression()->result_count() < 2)
2239
        {
2240
          Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2241
                                                              loc);
2242
          s = ts;
2243
          *pexpr = Expression::make_temporary_reference(ts, loc);
2244
        }
2245
      else
2246
        {
2247
          // A call expression which returns multiple results needs to
2248
          // be handled specially.  We can't create a temporary
2249
          // because there is no type to give it.  Any actual uses of
2250
          // the values will be done via Call_result_expressions.
2251
          s = Statement::make_statement(*pexpr, true);
2252
        }
2253
 
2254
      block->insert_statement_before(*pindex, s);
2255
      ++*pindex;
2256
    }
2257
 
2258
  if (init != orig_init)
2259
    vds->var()->var_value()->set_init(init);
2260
 
2261
  return TRAVERSE_CONTINUE;
2262
}
2263
 
2264
// Implement the order of evaluation rules for the initializer of a
2265
// global variable.
2266
 
2267
int
2268
Order_eval::variable(Named_object* no)
2269
{
2270
  if (no->is_result_variable())
2271
    return TRAVERSE_CONTINUE;
2272
  Variable* var = no->var_value();
2273
  Expression* init = var->init();
2274
  if (!var->is_global() || init == NULL)
2275
    return TRAVERSE_CONTINUE;
2276
 
2277
  Find_eval_ordering find_eval_ordering;
2278
  Expression::traverse(&init, &find_eval_ordering);
2279
 
2280
  if (find_eval_ordering.size() <= 1)
2281
    {
2282
      // If there is only one expression with a side-effect, we can
2283
      // leave it in place.
2284
      return TRAVERSE_SKIP_COMPONENTS;
2285
    }
2286
 
2287
  Expression* orig_init = init;
2288
 
2289
  for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2290
       p != find_eval_ordering.end();
2291
       ++p)
2292
    {
2293
      Expression** pexpr = *p;
2294
      Location loc = (*pexpr)->location();
2295
      Statement* s;
2296
      if ((*pexpr)->call_expression() == NULL
2297
          || (*pexpr)->call_expression()->result_count() < 2)
2298
        {
2299
          Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2300
                                                              loc);
2301
          s = ts;
2302
          *pexpr = Expression::make_temporary_reference(ts, loc);
2303
        }
2304
      else
2305
        {
2306
          // A call expression which returns multiple results needs to
2307
          // be handled specially.
2308
          s = Statement::make_statement(*pexpr, true);
2309
        }
2310
      var->add_preinit_statement(this->gogo_, s);
2311
    }
2312
 
2313
  if (init != orig_init)
2314
    var->set_init(init);
2315
 
2316
  return TRAVERSE_SKIP_COMPONENTS;
2317
}
2318
 
2319
// Use temporary variables to implement the order of evaluation rules.
2320
 
2321
void
2322
Gogo::order_evaluations()
2323
{
2324
  Order_eval order_eval(this);
2325
  this->traverse(&order_eval);
2326
}
2327
 
2328
// Traversal to convert calls to the predeclared recover function to
2329
// pass in an argument indicating whether it can recover from a panic
2330
// or not.
2331
 
2332
class Convert_recover : public Traverse
2333
{
2334
 public:
2335
  Convert_recover(Named_object* arg)
2336
    : Traverse(traverse_expressions),
2337
      arg_(arg)
2338
  { }
2339
 
2340
 protected:
2341
  int
2342
  expression(Expression**);
2343
 
2344
 private:
2345
  // The argument to pass to the function.
2346
  Named_object* arg_;
2347
};
2348
 
2349
// Convert calls to recover.
2350
 
2351
int
2352
Convert_recover::expression(Expression** pp)
2353
{
2354
  Call_expression* ce = (*pp)->call_expression();
2355
  if (ce != NULL && ce->is_recover_call())
2356
    ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2357
                                                       ce->location()));
2358
  return TRAVERSE_CONTINUE;
2359
}
2360
 
2361
// Traversal for build_recover_thunks.
2362
 
2363
class Build_recover_thunks : public Traverse
2364
{
2365
 public:
2366
  Build_recover_thunks(Gogo* gogo)
2367
    : Traverse(traverse_functions),
2368
      gogo_(gogo)
2369
  { }
2370
 
2371
  int
2372
  function(Named_object*);
2373
 
2374
 private:
2375
  Expression*
2376
  can_recover_arg(Location);
2377
 
2378
  // General IR.
2379
  Gogo* gogo_;
2380
};
2381
 
2382
// If this function calls recover, turn it into a thunk.
2383
 
2384
int
2385
Build_recover_thunks::function(Named_object* orig_no)
2386
{
2387
  Function* orig_func = orig_no->func_value();
2388
  if (!orig_func->calls_recover()
2389
      || orig_func->is_recover_thunk()
2390
      || orig_func->has_recover_thunk())
2391
    return TRAVERSE_CONTINUE;
2392
 
2393
  Gogo* gogo = this->gogo_;
2394
  Location location = orig_func->location();
2395
 
2396
  static int count;
2397
  char buf[50];
2398
 
2399
  Function_type* orig_fntype = orig_func->type();
2400
  Typed_identifier_list* new_params = new Typed_identifier_list();
2401
  std::string receiver_name;
2402
  if (orig_fntype->is_method())
2403
    {
2404
      const Typed_identifier* receiver = orig_fntype->receiver();
2405
      snprintf(buf, sizeof buf, "rt.%u", count);
2406
      ++count;
2407
      receiver_name = buf;
2408
      new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2409
                                             receiver->location()));
2410
    }
2411
  const Typed_identifier_list* orig_params = orig_fntype->parameters();
2412
  if (orig_params != NULL && !orig_params->empty())
2413
    {
2414
      for (Typed_identifier_list::const_iterator p = orig_params->begin();
2415
           p != orig_params->end();
2416
           ++p)
2417
        {
2418
          snprintf(buf, sizeof buf, "pt.%u", count);
2419
          ++count;
2420
          new_params->push_back(Typed_identifier(buf, p->type(),
2421
                                                 p->location()));
2422
        }
2423
    }
2424
  snprintf(buf, sizeof buf, "pr.%u", count);
2425
  ++count;
2426
  std::string can_recover_name = buf;
2427
  new_params->push_back(Typed_identifier(can_recover_name,
2428
                                         Type::lookup_bool_type(),
2429
                                         orig_fntype->location()));
2430
 
2431
  const Typed_identifier_list* orig_results = orig_fntype->results();
2432
  Typed_identifier_list* new_results;
2433
  if (orig_results == NULL || orig_results->empty())
2434
    new_results = NULL;
2435
  else
2436
    {
2437
      new_results = new Typed_identifier_list();
2438
      for (Typed_identifier_list::const_iterator p = orig_results->begin();
2439
           p != orig_results->end();
2440
           ++p)
2441
        new_results->push_back(Typed_identifier("", p->type(), p->location()));
2442
    }
2443
 
2444
  Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2445
                                                       new_results,
2446
                                                       orig_fntype->location());
2447
  if (orig_fntype->is_varargs())
2448
    new_fntype->set_is_varargs();
2449
 
2450
  std::string name = orig_no->name() + "$recover";
2451
  Named_object *new_no = gogo->start_function(name, new_fntype, false,
2452
                                              location);
2453
  Function *new_func = new_no->func_value();
2454
  if (orig_func->enclosing() != NULL)
2455
    new_func->set_enclosing(orig_func->enclosing());
2456
 
2457
  // We build the code for the original function attached to the new
2458
  // function, and then swap the original and new function bodies.
2459
  // This means that existing references to the original function will
2460
  // then refer to the new function.  That makes this code a little
2461
  // confusing, in that the reference to NEW_NO really refers to the
2462
  // other function, not the one we are building.
2463
 
2464
  Expression* closure = NULL;
2465
  if (orig_func->needs_closure())
2466
    {
2467
      Named_object* orig_closure_no = orig_func->closure_var();
2468
      Variable* orig_closure_var = orig_closure_no->var_value();
2469
      Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2470
                                       true, false, location);
2471
      snprintf(buf, sizeof buf, "closure.%u", count);
2472
      ++count;
2473
      Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2474
                                                                 new_var);
2475
      new_func->set_closure_var(new_closure_no);
2476
      closure = Expression::make_var_reference(new_closure_no, location);
2477
    }
2478
 
2479
  Expression* fn = Expression::make_func_reference(new_no, closure, location);
2480
 
2481
  Expression_list* args = new Expression_list();
2482
  if (new_params != NULL)
2483
    {
2484
      // Note that we skip the last parameter, which is the boolean
2485
      // indicating whether recover can succed.
2486
      for (Typed_identifier_list::const_iterator p = new_params->begin();
2487
           p + 1 != new_params->end();
2488
           ++p)
2489
        {
2490
          Named_object* p_no = gogo->lookup(p->name(), NULL);
2491
          go_assert(p_no != NULL
2492
                     && p_no->is_variable()
2493
                     && p_no->var_value()->is_parameter());
2494
          args->push_back(Expression::make_var_reference(p_no, location));
2495
        }
2496
    }
2497
  args->push_back(this->can_recover_arg(location));
2498
 
2499
  gogo->start_block(location);
2500
 
2501
  Call_expression* call = Expression::make_call(fn, args, false, location);
2502
 
2503
  Statement* s;
2504
  if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2505
    s = Statement::make_statement(call, true);
2506
  else
2507
    {
2508
      Expression_list* vals = new Expression_list();
2509
      size_t rc = orig_fntype->results()->size();
2510
      if (rc == 1)
2511
        vals->push_back(call);
2512
      else
2513
        {
2514
          for (size_t i = 0; i < rc; ++i)
2515
            vals->push_back(Expression::make_call_result(call, i));
2516
        }
2517
      s = Statement::make_return_statement(vals, location);
2518
    }
2519
  s->determine_types();
2520
  gogo->add_statement(s);
2521
 
2522
  Block* b = gogo->finish_block(location);
2523
 
2524
  gogo->add_block(b, location);
2525
 
2526
  // Lower the call in case it returns multiple results.
2527
  gogo->lower_block(new_no, b);
2528
 
2529
  gogo->finish_function(location);
2530
 
2531
  // Swap the function bodies and types.
2532
  new_func->swap_for_recover(orig_func);
2533
  orig_func->set_is_recover_thunk();
2534
  new_func->set_calls_recover();
2535
  new_func->set_has_recover_thunk();
2536
 
2537
  Bindings* orig_bindings = orig_func->block()->bindings();
2538
  Bindings* new_bindings = new_func->block()->bindings();
2539
  if (orig_fntype->is_method())
2540
    {
2541
      // We changed the receiver to be a regular parameter.  We have
2542
      // to update the binding accordingly in both functions.
2543
      Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2544
      go_assert(orig_rec_no != NULL
2545
                 && orig_rec_no->is_variable()
2546
                 && !orig_rec_no->var_value()->is_receiver());
2547
      orig_rec_no->var_value()->set_is_receiver();
2548
 
2549
      const std::string& new_receiver_name(orig_fntype->receiver()->name());
2550
      Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2551
      if (new_rec_no == NULL)
2552
        go_assert(saw_errors());
2553
      else
2554
        {
2555
          go_assert(new_rec_no->is_variable()
2556
                     && new_rec_no->var_value()->is_receiver());
2557
          new_rec_no->var_value()->set_is_not_receiver();
2558
        }
2559
    }
2560
 
2561
  // Because we flipped blocks but not types, the can_recover
2562
  // parameter appears in the (now) old bindings as a parameter.
2563
  // Change it to a local variable, whereupon it will be discarded.
2564
  Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2565
  go_assert(can_recover_no != NULL
2566
             && can_recover_no->is_variable()
2567
             && can_recover_no->var_value()->is_parameter());
2568
  orig_bindings->remove_binding(can_recover_no);
2569
 
2570
  // Add the can_recover argument to the (now) new bindings, and
2571
  // attach it to any recover statements.
2572
  Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2573
                                           false, true, false, location);
2574
  can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2575
                                              can_recover_var);
2576
  Convert_recover convert_recover(can_recover_no);
2577
  new_func->traverse(&convert_recover);
2578
 
2579
  // Update the function pointers in any named results.
2580
  new_func->update_result_variables();
2581
  orig_func->update_result_variables();
2582
 
2583
  return TRAVERSE_CONTINUE;
2584
}
2585
 
2586
// Return the expression to pass for the .can_recover parameter to the
2587
// new function.  This indicates whether a call to recover may return
2588
// non-nil.  The expression is
2589
// __go_can_recover(__builtin_return_address()).
2590
 
2591
Expression*
2592
Build_recover_thunks::can_recover_arg(Location location)
2593
{
2594
  static Named_object* builtin_return_address;
2595
  if (builtin_return_address == NULL)
2596
    {
2597
      const Location bloc = Linemap::predeclared_location();
2598
 
2599
      Typed_identifier_list* param_types = new Typed_identifier_list();
2600
      Type* uint_type = Type::lookup_integer_type("uint");
2601
      param_types->push_back(Typed_identifier("l", uint_type, bloc));
2602
 
2603
      Typed_identifier_list* return_types = new Typed_identifier_list();
2604
      Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2605
      return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2606
 
2607
      Function_type* fntype = Type::make_function_type(NULL, param_types,
2608
                                                       return_types, bloc);
2609
      builtin_return_address =
2610
        Named_object::make_function_declaration("__builtin_return_address",
2611
                                                NULL, fntype, bloc);
2612
      const char* n = "__builtin_return_address";
2613
      builtin_return_address->func_declaration_value()->set_asm_name(n);
2614
    }
2615
 
2616
  static Named_object* can_recover;
2617
  if (can_recover == NULL)
2618
    {
2619
      const Location bloc = Linemap::predeclared_location();
2620
      Typed_identifier_list* param_types = new Typed_identifier_list();
2621
      Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2622
      param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2623
      Type* boolean_type = Type::lookup_bool_type();
2624
      Typed_identifier_list* results = new Typed_identifier_list();
2625
      results->push_back(Typed_identifier("", boolean_type, bloc));
2626
      Function_type* fntype = Type::make_function_type(NULL, param_types,
2627
                                                       results, bloc);
2628
      can_recover = Named_object::make_function_declaration("__go_can_recover",
2629
                                                            NULL, fntype,
2630
                                                            bloc);
2631
      can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2632
    }
2633
 
2634
  Expression* fn = Expression::make_func_reference(builtin_return_address,
2635
                                                   NULL, location);
2636
 
2637
  mpz_t zval;
2638
  mpz_init_set_ui(zval, 0UL);
2639
  Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2640
  mpz_clear(zval);
2641
  Expression_list *args = new Expression_list();
2642
  args->push_back(zexpr);
2643
 
2644
  Expression* call = Expression::make_call(fn, args, false, location);
2645
 
2646
  args = new Expression_list();
2647
  args->push_back(call);
2648
 
2649
  fn = Expression::make_func_reference(can_recover, NULL, location);
2650
  return Expression::make_call(fn, args, false, location);
2651
}
2652
 
2653
// Build thunks for functions which call recover.  We build a new
2654
// function with an extra parameter, which is whether a call to
2655
// recover can succeed.  We then move the body of this function to
2656
// that one.  We then turn this function into a thunk which calls the
2657
// new one, passing the value of
2658
// __go_can_recover(__builtin_return_address()).  The function will be
2659
// marked as not splitting the stack.  This will cooperate with the
2660
// implementation of defer to make recover do the right thing.
2661
 
2662
void
2663
Gogo::build_recover_thunks()
2664
{
2665
  Build_recover_thunks build_recover_thunks(this);
2666
  this->traverse(&build_recover_thunks);
2667
}
2668
 
2669
// Look for named types to see whether we need to create an interface
2670
// method table.
2671
 
2672
class Build_method_tables : public Traverse
2673
{
2674
 public:
2675
  Build_method_tables(Gogo* gogo,
2676
                      const std::vector<Interface_type*>& interfaces)
2677
    : Traverse(traverse_types),
2678
      gogo_(gogo), interfaces_(interfaces)
2679
  { }
2680
 
2681
  int
2682
  type(Type*);
2683
 
2684
 private:
2685
  // The IR.
2686
  Gogo* gogo_;
2687
  // A list of locally defined interfaces which have hidden methods.
2688
  const std::vector<Interface_type*>& interfaces_;
2689
};
2690
 
2691
// Build all required interface method tables for types.  We need to
2692
// ensure that we have an interface method table for every interface
2693
// which has a hidden method, for every named type which implements
2694
// that interface.  Normally we can just build interface method tables
2695
// as we need them.  However, in some cases we can require an
2696
// interface method table for an interface defined in a different
2697
// package for a type defined in that package.  If that interface and
2698
// type both use a hidden method, that is OK.  However, we will not be
2699
// able to build that interface method table when we need it, because
2700
// the type's hidden method will be static.  So we have to build it
2701
// here, and just refer it from other packages as needed.
2702
 
2703
void
2704
Gogo::build_interface_method_tables()
2705
{
2706
  if (saw_errors())
2707
    return;
2708
 
2709
  std::vector<Interface_type*> hidden_interfaces;
2710
  hidden_interfaces.reserve(this->interface_types_.size());
2711
  for (std::vector<Interface_type*>::const_iterator pi =
2712
         this->interface_types_.begin();
2713
       pi != this->interface_types_.end();
2714
       ++pi)
2715
    {
2716
      const Typed_identifier_list* methods = (*pi)->methods();
2717
      if (methods == NULL)
2718
        continue;
2719
      for (Typed_identifier_list::const_iterator pm = methods->begin();
2720
           pm != methods->end();
2721
           ++pm)
2722
        {
2723
          if (Gogo::is_hidden_name(pm->name()))
2724
            {
2725
              hidden_interfaces.push_back(*pi);
2726
              break;
2727
            }
2728
        }
2729
    }
2730
 
2731
  if (!hidden_interfaces.empty())
2732
    {
2733
      // Now traverse the tree looking for all named types.
2734
      Build_method_tables bmt(this, hidden_interfaces);
2735
      this->traverse(&bmt);
2736
    }
2737
 
2738
  // We no longer need the list of interfaces.
2739
 
2740
  this->interface_types_.clear();
2741
}
2742
 
2743
// This is called for each type.  For a named type, for each of the
2744
// interfaces with hidden methods that it implements, create the
2745
// method table.
2746
 
2747
int
2748
Build_method_tables::type(Type* type)
2749
{
2750
  Named_type* nt = type->named_type();
2751
  if (nt != NULL)
2752
    {
2753
      for (std::vector<Interface_type*>::const_iterator p =
2754
             this->interfaces_.begin();
2755
           p != this->interfaces_.end();
2756
           ++p)
2757
        {
2758
          // We ask whether a pointer to the named type implements the
2759
          // interface, because a pointer can implement more methods
2760
          // than a value.
2761
          if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2762
            {
2763
              nt->interface_method_table(this->gogo_, *p, false);
2764
              nt->interface_method_table(this->gogo_, *p, true);
2765
            }
2766
        }
2767
    }
2768
  return TRAVERSE_CONTINUE;
2769
}
2770
 
2771
// Traversal class used to check for return statements.
2772
 
2773
class Check_return_statements_traverse : public Traverse
2774
{
2775
 public:
2776
  Check_return_statements_traverse()
2777
    : Traverse(traverse_functions)
2778
  { }
2779
 
2780
  int
2781
  function(Named_object*);
2782
};
2783
 
2784
// Check that a function has a return statement if it needs one.
2785
 
2786
int
2787
Check_return_statements_traverse::function(Named_object* no)
2788
{
2789
  Function* func = no->func_value();
2790
  const Function_type* fntype = func->type();
2791
  const Typed_identifier_list* results = fntype->results();
2792
 
2793
  // We only need a return statement if there is a return value.
2794
  if (results == NULL || results->empty())
2795
    return TRAVERSE_CONTINUE;
2796
 
2797
  if (func->block()->may_fall_through())
2798
    error_at(func->location(), "control reaches end of non-void function");
2799
 
2800
  return TRAVERSE_CONTINUE;
2801
}
2802
 
2803
// Check return statements.
2804
 
2805
void
2806
Gogo::check_return_statements()
2807
{
2808
  Check_return_statements_traverse traverse;
2809
  this->traverse(&traverse);
2810
}
2811
 
2812
// Get the unique prefix to use before all exported symbols.  This
2813
// must be unique across the entire link.
2814
 
2815
const std::string&
2816
Gogo::unique_prefix() const
2817
{
2818
  go_assert(!this->unique_prefix_.empty());
2819
  return this->unique_prefix_;
2820
}
2821
 
2822
// Set the unique prefix to use before all exported symbols.  This
2823
// comes from the command line option -fgo-prefix=XXX.
2824
 
2825
void
2826
Gogo::set_unique_prefix(const std::string& arg)
2827
{
2828
  go_assert(this->unique_prefix_.empty());
2829
  this->unique_prefix_ = arg;
2830
  this->unique_prefix_specified_ = true;
2831
}
2832
 
2833
// Work out the package priority.  It is one more than the maximum
2834
// priority of an imported package.
2835
 
2836
int
2837
Gogo::package_priority() const
2838
{
2839
  int priority = 0;
2840
  for (Packages::const_iterator p = this->packages_.begin();
2841
       p != this->packages_.end();
2842
       ++p)
2843
    if (p->second->priority() > priority)
2844
      priority = p->second->priority();
2845
  return priority + 1;
2846
}
2847
 
2848
// Export identifiers as requested.
2849
 
2850
void
2851
Gogo::do_exports()
2852
{
2853
  // For now we always stream to a section.  Later we may want to
2854
  // support streaming to a separate file.
2855
  Stream_to_section stream;
2856
 
2857
  Export exp(&stream);
2858
  exp.register_builtin_types(this);
2859
  exp.export_globals(this->package_name(),
2860
                     this->unique_prefix(),
2861
                     this->package_priority(),
2862
                     this->imports_,
2863
                     (this->need_init_fn_ && !this->is_main_package()
2864
                      ? this->get_init_fn_name()
2865
                      : ""),
2866
                     this->imported_init_fns_,
2867
                     this->package_->bindings());
2868
}
2869
 
2870
// Find the blocks in order to convert named types defined in blocks.
2871
 
2872
class Convert_named_types : public Traverse
2873
{
2874
 public:
2875
  Convert_named_types(Gogo* gogo)
2876
    : Traverse(traverse_blocks),
2877
      gogo_(gogo)
2878
  { }
2879
 
2880
 protected:
2881
  int
2882
  block(Block* block);
2883
 
2884
 private:
2885
  Gogo* gogo_;
2886
};
2887
 
2888
int
2889
Convert_named_types::block(Block* block)
2890
{
2891
  this->gogo_->convert_named_types_in_bindings(block->bindings());
2892
  return TRAVERSE_CONTINUE;
2893
}
2894
 
2895
// Convert all named types to the backend representation.  Since named
2896
// types can refer to other types, this needs to be done in the right
2897
// sequence, which is handled by Named_type::convert.  Here we arrange
2898
// to call that for each named type.
2899
 
2900
void
2901
Gogo::convert_named_types()
2902
{
2903
  this->convert_named_types_in_bindings(this->globals_);
2904
  for (Packages::iterator p = this->packages_.begin();
2905
       p != this->packages_.end();
2906
       ++p)
2907
    {
2908
      Package* package = p->second;
2909
      this->convert_named_types_in_bindings(package->bindings());
2910
    }
2911
 
2912
  Convert_named_types cnt(this);
2913
  this->traverse(&cnt);
2914
 
2915
  // Make all the builtin named types used for type descriptors, and
2916
  // then convert them.  They will only be written out if they are
2917
  // needed.
2918
  Type::make_type_descriptor_type();
2919
  Type::make_type_descriptor_ptr_type();
2920
  Function_type::make_function_type_descriptor_type();
2921
  Pointer_type::make_pointer_type_descriptor_type();
2922
  Struct_type::make_struct_type_descriptor_type();
2923
  Array_type::make_array_type_descriptor_type();
2924
  Array_type::make_slice_type_descriptor_type();
2925
  Map_type::make_map_type_descriptor_type();
2926
  Map_type::make_map_descriptor_type();
2927
  Channel_type::make_chan_type_descriptor_type();
2928
  Interface_type::make_interface_type_descriptor_type();
2929
  Type::convert_builtin_named_types(this);
2930
 
2931
  Runtime::convert_types(this);
2932
 
2933
  this->named_types_are_converted_ = true;
2934
}
2935
 
2936
// Convert all names types in a set of bindings.
2937
 
2938
void
2939
Gogo::convert_named_types_in_bindings(Bindings* bindings)
2940
{
2941
  for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2942
       p != bindings->end_definitions();
2943
       ++p)
2944
    {
2945
      if ((*p)->is_type())
2946
        (*p)->type_value()->convert(this);
2947
    }
2948
}
2949
 
2950
// Class Function.
2951
 
2952
Function::Function(Function_type* type, Function* enclosing, Block* block,
2953
                   Location location)
2954
  : type_(type), enclosing_(enclosing), results_(NULL),
2955
    closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2956
    defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2957
    is_recover_thunk_(false), has_recover_thunk_(false)
2958
{
2959
}
2960
 
2961
// Create the named result variables.
2962
 
2963
void
2964
Function::create_result_variables(Gogo* gogo)
2965
{
2966
  const Typed_identifier_list* results = this->type_->results();
2967
  if (results == NULL || results->empty())
2968
    return;
2969
 
2970
  if (!results->front().name().empty())
2971
    this->results_are_named_ = true;
2972
 
2973
  this->results_ = new Results();
2974
  this->results_->reserve(results->size());
2975
 
2976
  Block* block = this->block_;
2977
  int index = 0;
2978
  for (Typed_identifier_list::const_iterator p = results->begin();
2979
       p != results->end();
2980
       ++p, ++index)
2981
    {
2982
      std::string name = p->name();
2983
      if (name.empty() || Gogo::is_sink_name(name))
2984
        {
2985
          static int result_counter;
2986
          char buf[100];
2987
          snprintf(buf, sizeof buf, "$ret%d", result_counter);
2988
          ++result_counter;
2989
          name = gogo->pack_hidden_name(buf, false);
2990
        }
2991
      Result_variable* result = new Result_variable(p->type(), this, index,
2992
                                                    p->location());
2993
      Named_object* no = block->bindings()->add_result_variable(name, result);
2994
      if (no->is_result_variable())
2995
        this->results_->push_back(no);
2996
      else
2997
        {
2998
          static int dummy_result_count;
2999
          char buf[100];
3000
          snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
3001
          ++dummy_result_count;
3002
          name = gogo->pack_hidden_name(buf, false);
3003
          no = block->bindings()->add_result_variable(name, result);
3004
          go_assert(no->is_result_variable());
3005
          this->results_->push_back(no);
3006
        }
3007
    }
3008
}
3009
 
3010
// Update the named result variables when cloning a function which
3011
// calls recover.
3012
 
3013
void
3014
Function::update_result_variables()
3015
{
3016
  if (this->results_ == NULL)
3017
    return;
3018
 
3019
  for (Results::iterator p = this->results_->begin();
3020
       p != this->results_->end();
3021
       ++p)
3022
    (*p)->result_var_value()->set_function(this);
3023
}
3024
 
3025
// Return the closure variable, creating it if necessary.
3026
 
3027
Named_object*
3028
Function::closure_var()
3029
{
3030
  if (this->closure_var_ == NULL)
3031
    {
3032
      // We don't know the type of the variable yet.  We add fields as
3033
      // we find them.
3034
      Location loc = this->type_->location();
3035
      Struct_field_list* sfl = new Struct_field_list;
3036
      Type* struct_type = Type::make_struct_type(sfl, loc);
3037
      Variable* var = new Variable(Type::make_pointer_type(struct_type),
3038
                                   NULL, false, true, false, loc);
3039
      var->set_is_used();
3040
      this->closure_var_ = Named_object::make_variable("closure", NULL, var);
3041
      // Note that the new variable is not in any binding contour.
3042
    }
3043
  return this->closure_var_;
3044
}
3045
 
3046
// Set the type of the closure variable.
3047
 
3048
void
3049
Function::set_closure_type()
3050
{
3051
  if (this->closure_var_ == NULL)
3052
    return;
3053
  Named_object* closure = this->closure_var_;
3054
  Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3055
  unsigned int index = 0;
3056
  for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3057
       p != this->closure_fields_.end();
3058
       ++p, ++index)
3059
    {
3060
      Named_object* no = p->first;
3061
      char buf[20];
3062
      snprintf(buf, sizeof buf, "%u", index);
3063
      std::string n = no->name() + buf;
3064
      Type* var_type;
3065
      if (no->is_variable())
3066
        var_type = no->var_value()->type();
3067
      else
3068
        var_type = no->result_var_value()->type();
3069
      Type* field_type = Type::make_pointer_type(var_type);
3070
      st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3071
    }
3072
}
3073
 
3074
// Return whether this function is a method.
3075
 
3076
bool
3077
Function::is_method() const
3078
{
3079
  return this->type_->is_method();
3080
}
3081
 
3082
// Add a label definition.
3083
 
3084
Label*
3085
Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3086
                               Location location)
3087
{
3088
  Label* lnull = NULL;
3089
  std::pair<Labels::iterator, bool> ins =
3090
    this->labels_.insert(std::make_pair(label_name, lnull));
3091
  Label* label;
3092
  if (ins.second)
3093
    {
3094
      // This is a new label.
3095
      label = new Label(label_name);
3096
      ins.first->second = label;
3097
    }
3098
  else
3099
    {
3100
      // The label was already in the hash table.
3101
      label = ins.first->second;
3102
      if (label->is_defined())
3103
        {
3104
          error_at(location, "label %qs already defined",
3105
                   Gogo::message_name(label_name).c_str());
3106
          inform(label->location(), "previous definition of %qs was here",
3107
                 Gogo::message_name(label_name).c_str());
3108
          return new Label(label_name);
3109
        }
3110
    }
3111
 
3112
  label->define(location, gogo->bindings_snapshot(location));
3113
 
3114
  // Issue any errors appropriate for any previous goto's to this
3115
  // label.
3116
  const std::vector<Bindings_snapshot*>& refs(label->refs());
3117
  for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3118
       p != refs.end();
3119
       ++p)
3120
    (*p)->check_goto_to(gogo->current_block());
3121
  label->clear_refs();
3122
 
3123
  return label;
3124
}
3125
 
3126
// Add a reference to a label.
3127
 
3128
Label*
3129
Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3130
                              Location location, bool issue_goto_errors)
3131
{
3132
  Label* lnull = NULL;
3133
  std::pair<Labels::iterator, bool> ins =
3134
    this->labels_.insert(std::make_pair(label_name, lnull));
3135
  Label* label;
3136
  if (!ins.second)
3137
    {
3138
      // The label was already in the hash table.
3139
      label = ins.first->second;
3140
    }
3141
  else
3142
    {
3143
      go_assert(ins.first->second == NULL);
3144
      label = new Label(label_name);
3145
      ins.first->second = label;
3146
    }
3147
 
3148
  label->set_is_used();
3149
 
3150
  if (issue_goto_errors)
3151
    {
3152
      Bindings_snapshot* snapshot = label->snapshot();
3153
      if (snapshot != NULL)
3154
        snapshot->check_goto_from(gogo->current_block(), location);
3155
      else
3156
        label->add_snapshot_ref(gogo->bindings_snapshot(location));
3157
    }
3158
 
3159
  return label;
3160
}
3161
 
3162
// Warn about labels that are defined but not used.
3163
 
3164
void
3165
Function::check_labels() const
3166
{
3167
  for (Labels::const_iterator p = this->labels_.begin();
3168
       p != this->labels_.end();
3169
       p++)
3170
    {
3171
      Label* label = p->second;
3172
      if (!label->is_used())
3173
        error_at(label->location(), "label %qs defined and not used",
3174
                 Gogo::message_name(label->name()).c_str());
3175
    }
3176
}
3177
 
3178
// Swap one function with another.  This is used when building the
3179
// thunk we use to call a function which calls recover.  It may not
3180
// work for any other case.
3181
 
3182
void
3183
Function::swap_for_recover(Function *x)
3184
{
3185
  go_assert(this->enclosing_ == x->enclosing_);
3186
  std::swap(this->results_, x->results_);
3187
  std::swap(this->closure_var_, x->closure_var_);
3188
  std::swap(this->block_, x->block_);
3189
  go_assert(this->location_ == x->location_);
3190
  go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3191
  go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3192
}
3193
 
3194
// Traverse the tree.
3195
 
3196
int
3197
Function::traverse(Traverse* traverse)
3198
{
3199
  unsigned int traverse_mask = traverse->traverse_mask();
3200
 
3201
  if ((traverse_mask
3202
       & (Traverse::traverse_types | Traverse::traverse_expressions))
3203
      != 0)
3204
    {
3205
      if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3206
        return TRAVERSE_EXIT;
3207
    }
3208
 
3209
  // FIXME: We should check traverse_functions here if nested
3210
  // functions are stored in block bindings.
3211
  if (this->block_ != NULL
3212
      && (traverse_mask
3213
          & (Traverse::traverse_variables
3214
             | Traverse::traverse_constants
3215
             | Traverse::traverse_blocks
3216
             | Traverse::traverse_statements
3217
             | Traverse::traverse_expressions
3218
             | Traverse::traverse_types)) != 0)
3219
    {
3220
      if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3221
        return TRAVERSE_EXIT;
3222
    }
3223
 
3224
  return TRAVERSE_CONTINUE;
3225
}
3226
 
3227
// Work out types for unspecified variables and constants.
3228
 
3229
void
3230
Function::determine_types()
3231
{
3232
  if (this->block_ != NULL)
3233
    this->block_->determine_types();
3234
}
3235
 
3236
// Get a pointer to the variable representing the defer stack for this
3237
// function, making it if necessary.  The value of the variable is set
3238
// by the runtime routines to true if the function is returning,
3239
// rather than panicing through.  A pointer to this variable is used
3240
// as a marker for the functions on the defer stack associated with
3241
// this function.  A function-specific variable permits inlining a
3242
// function which uses defer.
3243
 
3244
Expression*
3245
Function::defer_stack(Location location)
3246
{
3247
  if (this->defer_stack_ == NULL)
3248
    {
3249
      Type* t = Type::lookup_bool_type();
3250
      Expression* n = Expression::make_boolean(false, location);
3251
      this->defer_stack_ = Statement::make_temporary(t, n, location);
3252
      this->defer_stack_->set_is_address_taken();
3253
    }
3254
  Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3255
                                                         location);
3256
  return Expression::make_unary(OPERATOR_AND, ref, location);
3257
}
3258
 
3259
// Export the function.
3260
 
3261
void
3262
Function::export_func(Export* exp, const std::string& name) const
3263
{
3264
  Function::export_func_with_type(exp, name, this->type_);
3265
}
3266
 
3267
// Export a function with a type.
3268
 
3269
void
3270
Function::export_func_with_type(Export* exp, const std::string& name,
3271
                                const Function_type* fntype)
3272
{
3273
  exp->write_c_string("func ");
3274
 
3275
  if (fntype->is_method())
3276
    {
3277
      exp->write_c_string("(");
3278
      const Typed_identifier* receiver = fntype->receiver();
3279
      exp->write_name(receiver->name());
3280
      exp->write_c_string(" ");
3281
      exp->write_type(receiver->type());
3282
      exp->write_c_string(") ");
3283
    }
3284
 
3285
  exp->write_string(name);
3286
 
3287
  exp->write_c_string(" (");
3288
  const Typed_identifier_list* parameters = fntype->parameters();
3289
  if (parameters != NULL)
3290
    {
3291
      bool is_varargs = fntype->is_varargs();
3292
      bool first = true;
3293
      for (Typed_identifier_list::const_iterator p = parameters->begin();
3294
           p != parameters->end();
3295
           ++p)
3296
        {
3297
          if (first)
3298
            first = false;
3299
          else
3300
            exp->write_c_string(", ");
3301
          exp->write_name(p->name());
3302
          exp->write_c_string(" ");
3303
          if (!is_varargs || p + 1 != parameters->end())
3304
            exp->write_type(p->type());
3305
          else
3306
            {
3307
              exp->write_c_string("...");
3308
              exp->write_type(p->type()->array_type()->element_type());
3309
            }
3310
        }
3311
    }
3312
  exp->write_c_string(")");
3313
 
3314
  const Typed_identifier_list* results = fntype->results();
3315
  if (results != NULL)
3316
    {
3317
      if (results->size() == 1 && results->begin()->name().empty())
3318
        {
3319
          exp->write_c_string(" ");
3320
          exp->write_type(results->begin()->type());
3321
        }
3322
      else
3323
        {
3324
          exp->write_c_string(" (");
3325
          bool first = true;
3326
          for (Typed_identifier_list::const_iterator p = results->begin();
3327
               p != results->end();
3328
               ++p)
3329
            {
3330
              if (first)
3331
                first = false;
3332
              else
3333
                exp->write_c_string(", ");
3334
              exp->write_name(p->name());
3335
              exp->write_c_string(" ");
3336
              exp->write_type(p->type());
3337
            }
3338
          exp->write_c_string(")");
3339
        }
3340
    }
3341
  exp->write_c_string(";\n");
3342
}
3343
 
3344
// Import a function.
3345
 
3346
void
3347
Function::import_func(Import* imp, std::string* pname,
3348
                      Typed_identifier** preceiver,
3349
                      Typed_identifier_list** pparameters,
3350
                      Typed_identifier_list** presults,
3351
                      bool* is_varargs)
3352
{
3353
  imp->require_c_string("func ");
3354
 
3355
  *preceiver = NULL;
3356
  if (imp->peek_char() == '(')
3357
    {
3358
      imp->require_c_string("(");
3359
      std::string name = imp->read_name();
3360
      imp->require_c_string(" ");
3361
      Type* rtype = imp->read_type();
3362
      *preceiver = new Typed_identifier(name, rtype, imp->location());
3363
      imp->require_c_string(") ");
3364
    }
3365
 
3366
  *pname = imp->read_identifier();
3367
 
3368
  Typed_identifier_list* parameters;
3369
  *is_varargs = false;
3370
  imp->require_c_string(" (");
3371
  if (imp->peek_char() == ')')
3372
    parameters = NULL;
3373
  else
3374
    {
3375
      parameters = new Typed_identifier_list();
3376
      while (true)
3377
        {
3378
          std::string name = imp->read_name();
3379
          imp->require_c_string(" ");
3380
 
3381
          if (imp->match_c_string("..."))
3382
            {
3383
              imp->advance(3);
3384
              *is_varargs = true;
3385
            }
3386
 
3387
          Type* ptype = imp->read_type();
3388
          if (*is_varargs)
3389
            ptype = Type::make_array_type(ptype, NULL);
3390
          parameters->push_back(Typed_identifier(name, ptype,
3391
                                                 imp->location()));
3392
          if (imp->peek_char() != ',')
3393
            break;
3394
          go_assert(!*is_varargs);
3395
          imp->require_c_string(", ");
3396
        }
3397
    }
3398
  imp->require_c_string(")");
3399
  *pparameters = parameters;
3400
 
3401
  Typed_identifier_list* results;
3402
  if (imp->peek_char() != ' ')
3403
    results = NULL;
3404
  else
3405
    {
3406
      results = new Typed_identifier_list();
3407
      imp->require_c_string(" ");
3408
      if (imp->peek_char() != '(')
3409
        {
3410
          Type* rtype = imp->read_type();
3411
          results->push_back(Typed_identifier("", rtype, imp->location()));
3412
        }
3413
      else
3414
        {
3415
          imp->require_c_string("(");
3416
          while (true)
3417
            {
3418
              std::string name = imp->read_name();
3419
              imp->require_c_string(" ");
3420
              Type* rtype = imp->read_type();
3421
              results->push_back(Typed_identifier(name, rtype,
3422
                                                  imp->location()));
3423
              if (imp->peek_char() != ',')
3424
                break;
3425
              imp->require_c_string(", ");
3426
            }
3427
          imp->require_c_string(")");
3428
        }
3429
    }
3430
  imp->require_c_string(";\n");
3431
  *presults = results;
3432
}
3433
 
3434
// Class Block.
3435
 
3436
Block::Block(Block* enclosing, Location location)
3437
  : enclosing_(enclosing), statements_(),
3438
    bindings_(new Bindings(enclosing == NULL
3439
                           ? NULL
3440
                           : enclosing->bindings())),
3441
    start_location_(location),
3442
    end_location_(UNKNOWN_LOCATION)
3443
{
3444
}
3445
 
3446
// Add a statement to a block.
3447
 
3448
void
3449
Block::add_statement(Statement* statement)
3450
{
3451
  this->statements_.push_back(statement);
3452
}
3453
 
3454
// Add a statement to the front of a block.  This is slow but is only
3455
// used for reference counts of parameters.
3456
 
3457
void
3458
Block::add_statement_at_front(Statement* statement)
3459
{
3460
  this->statements_.insert(this->statements_.begin(), statement);
3461
}
3462
 
3463
// Replace a statement in a block.
3464
 
3465
void
3466
Block::replace_statement(size_t index, Statement* s)
3467
{
3468
  go_assert(index < this->statements_.size());
3469
  this->statements_[index] = s;
3470
}
3471
 
3472
// Add a statement before another statement.
3473
 
3474
void
3475
Block::insert_statement_before(size_t index, Statement* s)
3476
{
3477
  go_assert(index < this->statements_.size());
3478
  this->statements_.insert(this->statements_.begin() + index, s);
3479
}
3480
 
3481
// Add a statement after another statement.
3482
 
3483
void
3484
Block::insert_statement_after(size_t index, Statement* s)
3485
{
3486
  go_assert(index < this->statements_.size());
3487
  this->statements_.insert(this->statements_.begin() + index + 1, s);
3488
}
3489
 
3490
// Traverse the tree.
3491
 
3492
int
3493
Block::traverse(Traverse* traverse)
3494
{
3495
  unsigned int traverse_mask = traverse->traverse_mask();
3496
 
3497
  if ((traverse_mask & Traverse::traverse_blocks) != 0)
3498
    {
3499
      int t = traverse->block(this);
3500
      if (t == TRAVERSE_EXIT)
3501
        return TRAVERSE_EXIT;
3502
      else if (t == TRAVERSE_SKIP_COMPONENTS)
3503
        return TRAVERSE_CONTINUE;
3504
    }
3505
 
3506
  if ((traverse_mask
3507
       & (Traverse::traverse_variables
3508
          | Traverse::traverse_constants
3509
          | Traverse::traverse_expressions
3510
          | Traverse::traverse_types)) != 0)
3511
    {
3512
      const unsigned int e_or_t = (Traverse::traverse_expressions
3513
                                   | Traverse::traverse_types);
3514
      const unsigned int e_or_t_or_s = (e_or_t
3515
                                        | Traverse::traverse_statements);
3516
      for (Bindings::const_definitions_iterator pb =
3517
             this->bindings_->begin_definitions();
3518
           pb != this->bindings_->end_definitions();
3519
           ++pb)
3520
        {
3521
          int t = TRAVERSE_CONTINUE;
3522
          switch ((*pb)->classification())
3523
            {
3524
            case Named_object::NAMED_OBJECT_CONST:
3525
              if ((traverse_mask & Traverse::traverse_constants) != 0)
3526
                t = traverse->constant(*pb, false);
3527
              if (t == TRAVERSE_CONTINUE
3528
                  && (traverse_mask & e_or_t) != 0)
3529
                {
3530
                  Type* tc = (*pb)->const_value()->type();
3531
                  if (tc != NULL
3532
                      && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3533
                    return TRAVERSE_EXIT;
3534
                  t = (*pb)->const_value()->traverse_expression(traverse);
3535
                }
3536
              break;
3537
 
3538
            case Named_object::NAMED_OBJECT_VAR:
3539
            case Named_object::NAMED_OBJECT_RESULT_VAR:
3540
              if ((traverse_mask & Traverse::traverse_variables) != 0)
3541
                t = traverse->variable(*pb);
3542
              if (t == TRAVERSE_CONTINUE
3543
                  && (traverse_mask & e_or_t) != 0)
3544
                {
3545
                  if ((*pb)->is_result_variable()
3546
                      || (*pb)->var_value()->has_type())
3547
                    {
3548
                      Type* tv = ((*pb)->is_variable()
3549
                                  ? (*pb)->var_value()->type()
3550
                                  : (*pb)->result_var_value()->type());
3551
                      if (tv != NULL
3552
                          && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3553
                        return TRAVERSE_EXIT;
3554
                    }
3555
                }
3556
              if (t == TRAVERSE_CONTINUE
3557
                  && (traverse_mask & e_or_t_or_s) != 0
3558
                  && (*pb)->is_variable())
3559
                t = (*pb)->var_value()->traverse_expression(traverse,
3560
                                                            traverse_mask);
3561
              break;
3562
 
3563
            case Named_object::NAMED_OBJECT_FUNC:
3564
            case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3565
              go_unreachable();
3566
 
3567
            case Named_object::NAMED_OBJECT_TYPE:
3568
              if ((traverse_mask & e_or_t) != 0)
3569
                t = Type::traverse((*pb)->type_value(), traverse);
3570
              break;
3571
 
3572
            case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3573
            case Named_object::NAMED_OBJECT_UNKNOWN:
3574
            case Named_object::NAMED_OBJECT_ERRONEOUS:
3575
              break;
3576
 
3577
            case Named_object::NAMED_OBJECT_PACKAGE:
3578
            case Named_object::NAMED_OBJECT_SINK:
3579
              go_unreachable();
3580
 
3581
            default:
3582
              go_unreachable();
3583
            }
3584
 
3585
          if (t == TRAVERSE_EXIT)
3586
            return TRAVERSE_EXIT;
3587
        }
3588
    }
3589
 
3590
  // No point in checking traverse_mask here--if we got here we always
3591
  // want to walk the statements.  The traversal can insert new
3592
  // statements before or after the current statement.  Inserting
3593
  // statements before the current statement requires updating I via
3594
  // the pointer; those statements will not be traversed.  Any new
3595
  // statements inserted after the current statement will be traversed
3596
  // in their turn.
3597
  for (size_t i = 0; i < this->statements_.size(); ++i)
3598
    {
3599
      if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3600
        return TRAVERSE_EXIT;
3601
    }
3602
 
3603
  return TRAVERSE_CONTINUE;
3604
}
3605
 
3606
// Work out types for unspecified variables and constants.
3607
 
3608
void
3609
Block::determine_types()
3610
{
3611
  for (Bindings::const_definitions_iterator pb =
3612
         this->bindings_->begin_definitions();
3613
       pb != this->bindings_->end_definitions();
3614
       ++pb)
3615
    {
3616
      if ((*pb)->is_variable())
3617
        (*pb)->var_value()->determine_type();
3618
      else if ((*pb)->is_const())
3619
        (*pb)->const_value()->determine_type();
3620
    }
3621
 
3622
  for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3623
       ps != this->statements_.end();
3624
       ++ps)
3625
    (*ps)->determine_types();
3626
}
3627
 
3628
// Return true if the statements in this block may fall through.
3629
 
3630
bool
3631
Block::may_fall_through() const
3632
{
3633
  if (this->statements_.empty())
3634
    return true;
3635
  return this->statements_.back()->may_fall_through();
3636
}
3637
 
3638
// Convert a block to the backend representation.
3639
 
3640
Bblock*
3641
Block::get_backend(Translate_context* context)
3642
{
3643
  Gogo* gogo = context->gogo();
3644
  Named_object* function = context->function();
3645
  std::vector<Bvariable*> vars;
3646
  vars.reserve(this->bindings_->size_definitions());
3647
  for (Bindings::const_definitions_iterator pv =
3648
         this->bindings_->begin_definitions();
3649
       pv != this->bindings_->end_definitions();
3650
       ++pv)
3651
    {
3652
      if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3653
        vars.push_back((*pv)->get_backend_variable(gogo, function));
3654
    }
3655
 
3656
  // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3657
  // until we have a proper representation of the init function.
3658
  Bfunction* bfunction;
3659
  if (function == NULL)
3660
    bfunction = NULL;
3661
  else
3662
    bfunction = tree_to_function(function->func_value()->get_decl());
3663
  Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3664
                                          vars, this->start_location_,
3665
                                          this->end_location_);
3666
 
3667
  Translate_context subcontext(gogo, function, this, ret);
3668
  std::vector<Bstatement*> bstatements;
3669
  bstatements.reserve(this->statements_.size());
3670
  for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3671
       p != this->statements_.end();
3672
       ++p)
3673
    bstatements.push_back((*p)->get_backend(&subcontext));
3674
 
3675
  context->backend()->block_add_statements(ret, bstatements);
3676
 
3677
  return ret;
3678
}
3679
 
3680
// Class Bindings_snapshot.
3681
 
3682
Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
3683
  : block_(b), counts_(), location_(location)
3684
{
3685
  while (b != NULL)
3686
    {
3687
      this->counts_.push_back(b->bindings()->size_definitions());
3688
      b = b->enclosing();
3689
    }
3690
}
3691
 
3692
// Report errors appropriate for a goto from B to this.
3693
 
3694
void
3695
Bindings_snapshot::check_goto_from(const Block* b, Location loc)
3696
{
3697
  size_t dummy;
3698
  if (!this->check_goto_block(loc, b, this->block_, &dummy))
3699
    return;
3700
  this->check_goto_defs(loc, this->block_,
3701
                        this->block_->bindings()->size_definitions(),
3702
                        this->counts_[0]);
3703
}
3704
 
3705
// Report errors appropriate for a goto from this to B.
3706
 
3707
void
3708
Bindings_snapshot::check_goto_to(const Block* b)
3709
{
3710
  size_t index;
3711
  if (!this->check_goto_block(this->location_, this->block_, b, &index))
3712
    return;
3713
  this->check_goto_defs(this->location_, b, this->counts_[index],
3714
                        b->bindings()->size_definitions());
3715
}
3716
 
3717
// Report errors appropriate for a goto at LOC from BFROM to BTO.
3718
// Return true if all is well, false if we reported an error.  If this
3719
// returns true, it sets *PINDEX to the number of blocks BTO is above
3720
// BFROM.
3721
 
3722
bool
3723
Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
3724
                                    const Block* bto, size_t* pindex)
3725
{
3726
  // It is an error if BTO is not either BFROM or above BFROM.
3727
  size_t index = 0;
3728
  for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
3729
    {
3730
      if (pb == NULL)
3731
        {
3732
          error_at(loc, "goto jumps into block");
3733
          inform(bto->start_location(), "goto target block starts here");
3734
          return false;
3735
        }
3736
    }
3737
  *pindex = index;
3738
  return true;
3739
}
3740
 
3741
// Report errors appropriate for a goto at LOC ending at BLOCK, where
3742
// CFROM is the number of names defined at the point of the goto and
3743
// CTO is the number of names defined at the point of the label.
3744
 
3745
void
3746
Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
3747
                                   size_t cfrom, size_t cto)
3748
{
3749
  if (cfrom < cto)
3750
    {
3751
      Bindings::const_definitions_iterator p =
3752
        block->bindings()->begin_definitions();
3753
      for (size_t i = 0; i < cfrom; ++i)
3754
        {
3755
          go_assert(p != block->bindings()->end_definitions());
3756
          ++p;
3757
        }
3758
      go_assert(p != block->bindings()->end_definitions());
3759
 
3760
      std::string n = (*p)->message_name();
3761
      error_at(loc, "goto jumps over declaration of %qs", n.c_str());
3762
      inform((*p)->location(), "%qs defined here", n.c_str());
3763
    }
3764
}
3765
 
3766
// Class Variable.
3767
 
3768
Variable::Variable(Type* type, Expression* init, bool is_global,
3769
                   bool is_parameter, bool is_receiver,
3770
                   Location location)
3771
  : type_(type), init_(init), preinit_(NULL), location_(location),
3772
    backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3773
    is_receiver_(is_receiver), is_varargs_parameter_(false), is_used_(false),
3774
    is_address_taken_(false), is_non_escaping_address_taken_(false),
3775
    seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
3776
    type_from_range_index_(false), type_from_range_value_(false),
3777
    type_from_chan_element_(false), is_type_switch_var_(false),
3778
    determined_type_(false)
3779
{
3780
  go_assert(type != NULL || init != NULL);
3781
  go_assert(!is_parameter || init == NULL);
3782
}
3783
 
3784
// Traverse the initializer expression.
3785
 
3786
int
3787
Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
3788
{
3789
  if (this->preinit_ != NULL)
3790
    {
3791
      if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3792
        return TRAVERSE_EXIT;
3793
    }
3794
  if (this->init_ != NULL
3795
      && ((traverse_mask
3796
           & (Traverse::traverse_expressions | Traverse::traverse_types))
3797
          != 0))
3798
    {
3799
      if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3800
        return TRAVERSE_EXIT;
3801
    }
3802
  return TRAVERSE_CONTINUE;
3803
}
3804
 
3805
// Lower the initialization expression after parsing is complete.
3806
 
3807
void
3808
Variable::lower_init_expression(Gogo* gogo, Named_object* function,
3809
                                Statement_inserter* inserter)
3810
{
3811
  if (this->init_ != NULL && !this->init_is_lowered_)
3812
    {
3813
      if (this->seen_)
3814
        {
3815
          // We will give an error elsewhere, this is just to prevent
3816
          // an infinite loop.
3817
          return;
3818
        }
3819
      this->seen_ = true;
3820
 
3821
      Statement_inserter global_inserter;
3822
      if (this->is_global_)
3823
        {
3824
          global_inserter = Statement_inserter(gogo, this);
3825
          inserter = &global_inserter;
3826
        }
3827
 
3828
      gogo->lower_expression(function, inserter, &this->init_);
3829
 
3830
      this->seen_ = false;
3831
 
3832
      this->init_is_lowered_ = true;
3833
    }
3834
}
3835
 
3836
// Get the preinit block.
3837
 
3838
Block*
3839
Variable::preinit_block(Gogo* gogo)
3840
{
3841
  go_assert(this->is_global_);
3842
  if (this->preinit_ == NULL)
3843
    this->preinit_ = new Block(NULL, this->location());
3844
 
3845
  // If a global variable has a preinitialization statement, then we
3846
  // need to have an initialization function.
3847
  gogo->set_need_init_fn();
3848
 
3849
  return this->preinit_;
3850
}
3851
 
3852
// Add a statement to be run before the initialization expression.
3853
 
3854
void
3855
Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3856
{
3857
  Block* b = this->preinit_block(gogo);
3858
  b->add_statement(s);
3859
  b->set_end_location(s->location());
3860
}
3861
 
3862
// Whether this variable has a type.
3863
 
3864
bool
3865
Variable::has_type() const
3866
{
3867
  if (this->type_ == NULL)
3868
    return false;
3869
 
3870
  // A variable created in a type switch case nil does not actually
3871
  // have a type yet.  It will be changed to use the initializer's
3872
  // type in determine_type.
3873
  if (this->is_type_switch_var_
3874
      && this->type_->is_nil_constant_as_type())
3875
    return false;
3876
 
3877
  return true;
3878
}
3879
 
3880
// In an assignment which sets a variable to a tuple of EXPR, return
3881
// the type of the first element of the tuple.
3882
 
3883
Type*
3884
Variable::type_from_tuple(Expression* expr, bool report_error) const
3885
{
3886
  if (expr->map_index_expression() != NULL)
3887
    {
3888
      Map_type* mt = expr->map_index_expression()->get_map_type();
3889
      if (mt == NULL)
3890
        return Type::make_error_type();
3891
      return mt->val_type();
3892
    }
3893
  else if (expr->receive_expression() != NULL)
3894
    {
3895
      Expression* channel = expr->receive_expression()->channel();
3896
      Type* channel_type = channel->type();
3897
      if (channel_type->channel_type() == NULL)
3898
        return Type::make_error_type();
3899
      return channel_type->channel_type()->element_type();
3900
    }
3901
  else
3902
    {
3903
      if (report_error)
3904
        error_at(this->location(), "invalid tuple definition");
3905
      return Type::make_error_type();
3906
    }
3907
}
3908
 
3909
// Given EXPR used in a range clause, return either the index type or
3910
// the value type of the range, depending upon GET_INDEX_TYPE.
3911
 
3912
Type*
3913
Variable::type_from_range(Expression* expr, bool get_index_type,
3914
                          bool report_error) const
3915
{
3916
  Type* t = expr->type();
3917
  if (t->array_type() != NULL
3918
      || (t->points_to() != NULL
3919
          && t->points_to()->array_type() != NULL
3920
          && !t->points_to()->is_slice_type()))
3921
    {
3922
      if (get_index_type)
3923
        return Type::lookup_integer_type("int");
3924
      else
3925
        return t->deref()->array_type()->element_type();
3926
    }
3927
  else if (t->is_string_type())
3928
    {
3929
      if (get_index_type)
3930
        return Type::lookup_integer_type("int");
3931
      else
3932
        return Type::lookup_integer_type("int32");
3933
    }
3934
  else if (t->map_type() != NULL)
3935
    {
3936
      if (get_index_type)
3937
        return t->map_type()->key_type();
3938
      else
3939
        return t->map_type()->val_type();
3940
    }
3941
  else if (t->channel_type() != NULL)
3942
    {
3943
      if (get_index_type)
3944
        return t->channel_type()->element_type();
3945
      else
3946
        {
3947
          if (report_error)
3948
            error_at(this->location(),
3949
                     "invalid definition of value variable for channel range");
3950
          return Type::make_error_type();
3951
        }
3952
    }
3953
  else
3954
    {
3955
      if (report_error)
3956
        error_at(this->location(), "invalid type for range clause");
3957
      return Type::make_error_type();
3958
    }
3959
}
3960
 
3961
// EXPR should be a channel.  Return the channel's element type.
3962
 
3963
Type*
3964
Variable::type_from_chan_element(Expression* expr, bool report_error) const
3965
{
3966
  Type* t = expr->type();
3967
  if (t->channel_type() != NULL)
3968
    return t->channel_type()->element_type();
3969
  else
3970
    {
3971
      if (report_error)
3972
        error_at(this->location(), "expected channel");
3973
      return Type::make_error_type();
3974
    }
3975
}
3976
 
3977
// Return the type of the Variable.  This may be called before
3978
// Variable::determine_type is called, which means that we may need to
3979
// get the type from the initializer.  FIXME: If we combine lowering
3980
// with type determination, then this should be unnecessary.
3981
 
3982
Type*
3983
Variable::type()
3984
{
3985
  // A variable in a type switch with a nil case will have the wrong
3986
  // type here.  This gets fixed up in determine_type, below.
3987
  Type* type = this->type_;
3988
  Expression* init = this->init_;
3989
  if (this->is_type_switch_var_
3990
      && this->type_->is_nil_constant_as_type())
3991
    {
3992
      Type_guard_expression* tge = this->init_->type_guard_expression();
3993
      go_assert(tge != NULL);
3994
      init = tge->expr();
3995
      type = NULL;
3996
    }
3997
 
3998
  if (this->seen_)
3999
    {
4000
      if (this->type_ == NULL || !this->type_->is_error_type())
4001
        {
4002
          error_at(this->location_, "variable initializer refers to itself");
4003
          this->type_ = Type::make_error_type();
4004
        }
4005
      return this->type_;
4006
    }
4007
 
4008
  this->seen_ = true;
4009
 
4010
  if (type != NULL)
4011
    ;
4012
  else if (this->type_from_init_tuple_)
4013
    type = this->type_from_tuple(init, false);
4014
  else if (this->type_from_range_index_ || this->type_from_range_value_)
4015
    type = this->type_from_range(init, this->type_from_range_index_, false);
4016
  else if (this->type_from_chan_element_)
4017
    type = this->type_from_chan_element(init, false);
4018
  else
4019
    {
4020
      go_assert(init != NULL);
4021
      type = init->type();
4022
      go_assert(type != NULL);
4023
 
4024
      // Variables should not have abstract types.
4025
      if (type->is_abstract())
4026
        type = type->make_non_abstract_type();
4027
 
4028
      if (type->is_void_type())
4029
        type = Type::make_error_type();
4030
    }
4031
 
4032
  this->seen_ = false;
4033
 
4034
  return type;
4035
}
4036
 
4037
// Fetch the type from a const pointer, in which case it should have
4038
// been set already.
4039
 
4040
Type*
4041
Variable::type() const
4042
{
4043
  go_assert(this->type_ != NULL);
4044
  return this->type_;
4045
}
4046
 
4047
// Set the type if necessary.
4048
 
4049
void
4050
Variable::determine_type()
4051
{
4052
  if (this->determined_type_)
4053
    return;
4054
  this->determined_type_ = true;
4055
 
4056
  if (this->preinit_ != NULL)
4057
    this->preinit_->determine_types();
4058
 
4059
  // A variable in a type switch with a nil case will have the wrong
4060
  // type here.  It will have an initializer which is a type guard.
4061
  // We want to initialize it to the value without the type guard, and
4062
  // use the type of that value as well.
4063
  if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
4064
    {
4065
      Type_guard_expression* tge = this->init_->type_guard_expression();
4066
      go_assert(tge != NULL);
4067
      this->type_ = NULL;
4068
      this->init_ = tge->expr();
4069
    }
4070
 
4071
  if (this->init_ == NULL)
4072
    go_assert(this->type_ != NULL && !this->type_->is_abstract());
4073
  else if (this->type_from_init_tuple_)
4074
    {
4075
      Expression *init = this->init_;
4076
      init->determine_type_no_context();
4077
      this->type_ = this->type_from_tuple(init, true);
4078
      this->init_ = NULL;
4079
    }
4080
  else if (this->type_from_range_index_ || this->type_from_range_value_)
4081
    {
4082
      Expression* init = this->init_;
4083
      init->determine_type_no_context();
4084
      this->type_ = this->type_from_range(init, this->type_from_range_index_,
4085
                                          true);
4086
      this->init_ = NULL;
4087
    }
4088
  else if (this->type_from_chan_element_)
4089
    {
4090
      Expression* init = this->init_;
4091
      init->determine_type_no_context();
4092
      this->type_ = this->type_from_chan_element(init, true);
4093
      this->init_ = NULL;
4094
    }
4095
  else
4096
    {
4097
      Type_context context(this->type_, false);
4098
      this->init_->determine_type(&context);
4099
      if (this->type_ == NULL)
4100
        {
4101
          Type* type = this->init_->type();
4102
          go_assert(type != NULL);
4103
          if (type->is_abstract())
4104
            type = type->make_non_abstract_type();
4105
 
4106
          if (type->is_void_type())
4107
            {
4108
              error_at(this->location_, "variable has no type");
4109
              type = Type::make_error_type();
4110
            }
4111
          else if (type->is_nil_type())
4112
            {
4113
              error_at(this->location_, "variable defined to nil type");
4114
              type = Type::make_error_type();
4115
            }
4116
          else if (type->is_call_multiple_result_type())
4117
            {
4118
              error_at(this->location_,
4119
                       "single variable set to multiple value function call");
4120
              type = Type::make_error_type();
4121
            }
4122
 
4123
          this->type_ = type;
4124
        }
4125
    }
4126
}
4127
 
4128
// Export the variable
4129
 
4130
void
4131
Variable::export_var(Export* exp, const std::string& name) const
4132
{
4133
  go_assert(this->is_global_);
4134
  exp->write_c_string("var ");
4135
  exp->write_string(name);
4136
  exp->write_c_string(" ");
4137
  exp->write_type(this->type());
4138
  exp->write_c_string(";\n");
4139
}
4140
 
4141
// Import a variable.
4142
 
4143
void
4144
Variable::import_var(Import* imp, std::string* pname, Type** ptype)
4145
{
4146
  imp->require_c_string("var ");
4147
  *pname = imp->read_identifier();
4148
  imp->require_c_string(" ");
4149
  *ptype = imp->read_type();
4150
  imp->require_c_string(";\n");
4151
}
4152
 
4153
// Convert a variable to the backend representation.
4154
 
4155
Bvariable*
4156
Variable::get_backend_variable(Gogo* gogo, Named_object* function,
4157
                               const Package* package, const std::string& name)
4158
{
4159
  if (this->backend_ == NULL)
4160
    {
4161
      Backend* backend = gogo->backend();
4162
      Type* type = this->type_;
4163
      if (type->is_error_type()
4164
          || (type->is_undefined()
4165
              && (!this->is_global_ || package == NULL)))
4166
        this->backend_ = backend->error_variable();
4167
      else
4168
        {
4169
          bool is_parameter = this->is_parameter_;
4170
          if (this->is_receiver_ && type->points_to() == NULL)
4171
            is_parameter = false;
4172
          if (this->is_in_heap())
4173
            {
4174
              is_parameter = false;
4175
              type = Type::make_pointer_type(type);
4176
            }
4177
 
4178
          std::string n = Gogo::unpack_hidden_name(name);
4179
          Btype* btype = type->get_backend(gogo);
4180
 
4181
          Bvariable* bvar;
4182
          if (this->is_global_)
4183
            bvar = backend->global_variable((package == NULL
4184
                                             ? gogo->package_name()
4185
                                             : package->name()),
4186
                                            (package == NULL
4187
                                             ? gogo->unique_prefix()
4188
                                             : package->unique_prefix()),
4189
                                            n,
4190
                                            btype,
4191
                                            package != NULL,
4192
                                            Gogo::is_hidden_name(name),
4193
                                            this->location_);
4194
          else if (function == NULL)
4195
            {
4196
              go_assert(saw_errors());
4197
              bvar = backend->error_variable();
4198
            }
4199
          else
4200
            {
4201
              tree fndecl = function->func_value()->get_decl();
4202
              Bfunction* bfunction = tree_to_function(fndecl);
4203
              bool is_address_taken = (this->is_non_escaping_address_taken_
4204
                                       && !this->is_in_heap());
4205
              if (is_parameter)
4206
                bvar = backend->parameter_variable(bfunction, n, btype,
4207
                                                   is_address_taken,
4208
                                                   this->location_);
4209
              else
4210
                bvar = backend->local_variable(bfunction, n, btype,
4211
                                               is_address_taken,
4212
                                               this->location_);
4213
            }
4214
          this->backend_ = bvar;
4215
        }
4216
    }
4217
  return this->backend_;
4218
}
4219
 
4220
// Class Result_variable.
4221
 
4222
// Convert a result variable to the backend representation.
4223
 
4224
Bvariable*
4225
Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
4226
                                      const std::string& name)
4227
{
4228
  if (this->backend_ == NULL)
4229
    {
4230
      Backend* backend = gogo->backend();
4231
      Type* type = this->type_;
4232
      if (type->is_error())
4233
        this->backend_ = backend->error_variable();
4234
      else
4235
        {
4236
          if (this->is_in_heap())
4237
            type = Type::make_pointer_type(type);
4238
          Btype* btype = type->get_backend(gogo);
4239
          tree fndecl = function->func_value()->get_decl();
4240
          Bfunction* bfunction = tree_to_function(fndecl);
4241
          std::string n = Gogo::unpack_hidden_name(name);
4242
          bool is_address_taken = (this->is_non_escaping_address_taken_
4243
                                   && !this->is_in_heap());
4244
          this->backend_ = backend->local_variable(bfunction, n, btype,
4245
                                                   is_address_taken,
4246
                                                   this->location_);
4247
        }
4248
    }
4249
  return this->backend_;
4250
}
4251
 
4252
// Class Named_constant.
4253
 
4254
// Traverse the initializer expression.
4255
 
4256
int
4257
Named_constant::traverse_expression(Traverse* traverse)
4258
{
4259
  return Expression::traverse(&this->expr_, traverse);
4260
}
4261
 
4262
// Determine the type of the constant.
4263
 
4264
void
4265
Named_constant::determine_type()
4266
{
4267
  if (this->type_ != NULL)
4268
    {
4269
      Type_context context(this->type_, false);
4270
      this->expr_->determine_type(&context);
4271
    }
4272
  else
4273
    {
4274
      // A constant may have an abstract type.
4275
      Type_context context(NULL, true);
4276
      this->expr_->determine_type(&context);
4277
      this->type_ = this->expr_->type();
4278
      go_assert(this->type_ != NULL);
4279
    }
4280
}
4281
 
4282
// Indicate that we found and reported an error for this constant.
4283
 
4284
void
4285
Named_constant::set_error()
4286
{
4287
  this->type_ = Type::make_error_type();
4288
  this->expr_ = Expression::make_error(this->location_);
4289
}
4290
 
4291
// Export a constant.
4292
 
4293
void
4294
Named_constant::export_const(Export* exp, const std::string& name) const
4295
{
4296
  exp->write_c_string("const ");
4297
  exp->write_string(name);
4298
  exp->write_c_string(" ");
4299
  if (!this->type_->is_abstract())
4300
    {
4301
      exp->write_type(this->type_);
4302
      exp->write_c_string(" ");
4303
    }
4304
  exp->write_c_string("= ");
4305
  this->expr()->export_expression(exp);
4306
  exp->write_c_string(";\n");
4307
}
4308
 
4309
// Import a constant.
4310
 
4311
void
4312
Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
4313
                             Expression** pexpr)
4314
{
4315
  imp->require_c_string("const ");
4316
  *pname = imp->read_identifier();
4317
  imp->require_c_string(" ");
4318
  if (imp->peek_char() == '=')
4319
    *ptype = NULL;
4320
  else
4321
    {
4322
      *ptype = imp->read_type();
4323
      imp->require_c_string(" ");
4324
    }
4325
  imp->require_c_string("= ");
4326
  *pexpr = Expression::import_expression(imp);
4327
  imp->require_c_string(";\n");
4328
}
4329
 
4330
// Add a method.
4331
 
4332
Named_object*
4333
Type_declaration::add_method(const std::string& name, Function* function)
4334
{
4335
  Named_object* ret = Named_object::make_function(name, NULL, function);
4336
  this->methods_.push_back(ret);
4337
  return ret;
4338
}
4339
 
4340
// Add a method declaration.
4341
 
4342
Named_object*
4343
Type_declaration::add_method_declaration(const std::string&  name,
4344
                                         Package* package,
4345
                                         Function_type* type,
4346
                                         Location location)
4347
{
4348
  Named_object* ret = Named_object::make_function_declaration(name, package,
4349
                                                              type, location);
4350
  this->methods_.push_back(ret);
4351
  return ret;
4352
}
4353
 
4354
// Return whether any methods ere defined.
4355
 
4356
bool
4357
Type_declaration::has_methods() const
4358
{
4359
  return !this->methods_.empty();
4360
}
4361
 
4362
// Define methods for the real type.
4363
 
4364
void
4365
Type_declaration::define_methods(Named_type* nt)
4366
{
4367
  for (Methods::const_iterator p = this->methods_.begin();
4368
       p != this->methods_.end();
4369
       ++p)
4370
    nt->add_existing_method(*p);
4371
}
4372
 
4373
// We are using the type.  Return true if we should issue a warning.
4374
 
4375
bool
4376
Type_declaration::using_type()
4377
{
4378
  bool ret = !this->issued_warning_;
4379
  this->issued_warning_ = true;
4380
  return ret;
4381
}
4382
 
4383
// Class Unknown_name.
4384
 
4385
// Set the real named object.
4386
 
4387
void
4388
Unknown_name::set_real_named_object(Named_object* no)
4389
{
4390
  go_assert(this->real_named_object_ == NULL);
4391
  go_assert(!no->is_unknown());
4392
  this->real_named_object_ = no;
4393
}
4394
 
4395
// Class Named_object.
4396
 
4397
Named_object::Named_object(const std::string& name,
4398
                           const Package* package,
4399
                           Classification classification)
4400
  : name_(name), package_(package), classification_(classification),
4401
    tree_(NULL)
4402
{
4403
  if (Gogo::is_sink_name(name))
4404
    go_assert(classification == NAMED_OBJECT_SINK);
4405
}
4406
 
4407
// Make an unknown name.  This is used by the parser.  The name must
4408
// be resolved later.  Unknown names are only added in the current
4409
// package.
4410
 
4411
Named_object*
4412
Named_object::make_unknown_name(const std::string& name,
4413
                                Location location)
4414
{
4415
  Named_object* named_object = new Named_object(name, NULL,
4416
                                                NAMED_OBJECT_UNKNOWN);
4417
  Unknown_name* value = new Unknown_name(location);
4418
  named_object->u_.unknown_value = value;
4419
  return named_object;
4420
}
4421
 
4422
// Make a constant.
4423
 
4424
Named_object*
4425
Named_object::make_constant(const Typed_identifier& tid,
4426
                            const Package* package, Expression* expr,
4427
                            int iota_value)
4428
{
4429
  Named_object* named_object = new Named_object(tid.name(), package,
4430
                                                NAMED_OBJECT_CONST);
4431
  Named_constant* named_constant = new Named_constant(tid.type(), expr,
4432
                                                      iota_value,
4433
                                                      tid.location());
4434
  named_object->u_.const_value = named_constant;
4435
  return named_object;
4436
}
4437
 
4438
// Make a named type.
4439
 
4440
Named_object*
4441
Named_object::make_type(const std::string& name, const Package* package,
4442
                        Type* type, Location location)
4443
{
4444
  Named_object* named_object = new Named_object(name, package,
4445
                                                NAMED_OBJECT_TYPE);
4446
  Named_type* named_type = Type::make_named_type(named_object, type, location);
4447
  named_object->u_.type_value = named_type;
4448
  return named_object;
4449
}
4450
 
4451
// Make a type declaration.
4452
 
4453
Named_object*
4454
Named_object::make_type_declaration(const std::string& name,
4455
                                    const Package* package,
4456
                                    Location location)
4457
{
4458
  Named_object* named_object = new Named_object(name, package,
4459
                                                NAMED_OBJECT_TYPE_DECLARATION);
4460
  Type_declaration* type_declaration = new Type_declaration(location);
4461
  named_object->u_.type_declaration = type_declaration;
4462
  return named_object;
4463
}
4464
 
4465
// Make a variable.
4466
 
4467
Named_object*
4468
Named_object::make_variable(const std::string& name, const Package* package,
4469
                            Variable* variable)
4470
{
4471
  Named_object* named_object = new Named_object(name, package,
4472
                                                NAMED_OBJECT_VAR);
4473
  named_object->u_.var_value = variable;
4474
  return named_object;
4475
}
4476
 
4477
// Make a result variable.
4478
 
4479
Named_object*
4480
Named_object::make_result_variable(const std::string& name,
4481
                                   Result_variable* result)
4482
{
4483
  Named_object* named_object = new Named_object(name, NULL,
4484
                                                NAMED_OBJECT_RESULT_VAR);
4485
  named_object->u_.result_var_value = result;
4486
  return named_object;
4487
}
4488
 
4489
// Make a sink.  This is used for the special blank identifier _.
4490
 
4491
Named_object*
4492
Named_object::make_sink()
4493
{
4494
  return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4495
}
4496
 
4497
// Make a named function.
4498
 
4499
Named_object*
4500
Named_object::make_function(const std::string& name, const Package* package,
4501
                            Function* function)
4502
{
4503
  Named_object* named_object = new Named_object(name, package,
4504
                                                NAMED_OBJECT_FUNC);
4505
  named_object->u_.func_value = function;
4506
  return named_object;
4507
}
4508
 
4509
// Make a function declaration.
4510
 
4511
Named_object*
4512
Named_object::make_function_declaration(const std::string& name,
4513
                                        const Package* package,
4514
                                        Function_type* fntype,
4515
                                        Location location)
4516
{
4517
  Named_object* named_object = new Named_object(name, package,
4518
                                                NAMED_OBJECT_FUNC_DECLARATION);
4519
  Function_declaration *func_decl = new Function_declaration(fntype, location);
4520
  named_object->u_.func_declaration_value = func_decl;
4521
  return named_object;
4522
}
4523
 
4524
// Make a package.
4525
 
4526
Named_object*
4527
Named_object::make_package(const std::string& alias, Package* package)
4528
{
4529
  Named_object* named_object = new Named_object(alias, NULL,
4530
                                                NAMED_OBJECT_PACKAGE);
4531
  named_object->u_.package_value = package;
4532
  return named_object;
4533
}
4534
 
4535
// Return the name to use in an error message.
4536
 
4537
std::string
4538
Named_object::message_name() const
4539
{
4540
  if (this->package_ == NULL)
4541
    return Gogo::message_name(this->name_);
4542
  std::string ret = Gogo::message_name(this->package_->name());
4543
  ret += '.';
4544
  ret += Gogo::message_name(this->name_);
4545
  return ret;
4546
}
4547
 
4548
// Set the type when a declaration is defined.
4549
 
4550
void
4551
Named_object::set_type_value(Named_type* named_type)
4552
{
4553
  go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4554
  Type_declaration* td = this->u_.type_declaration;
4555
  td->define_methods(named_type);
4556
  Named_object* in_function = td->in_function();
4557
  if (in_function != NULL)
4558
    named_type->set_in_function(in_function);
4559
  delete td;
4560
  this->classification_ = NAMED_OBJECT_TYPE;
4561
  this->u_.type_value = named_type;
4562
}
4563
 
4564
// Define a function which was previously declared.
4565
 
4566
void
4567
Named_object::set_function_value(Function* function)
4568
{
4569
  go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4570
  this->classification_ = NAMED_OBJECT_FUNC;
4571
  // FIXME: We should free the old value.
4572
  this->u_.func_value = function;
4573
}
4574
 
4575
// Declare an unknown object as a type declaration.
4576
 
4577
void
4578
Named_object::declare_as_type()
4579
{
4580
  go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4581
  Unknown_name* unk = this->u_.unknown_value;
4582
  this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4583
  this->u_.type_declaration = new Type_declaration(unk->location());
4584
  delete unk;
4585
}
4586
 
4587
// Return the location of a named object.
4588
 
4589
Location
4590
Named_object::location() const
4591
{
4592
  switch (this->classification_)
4593
    {
4594
    default:
4595
    case NAMED_OBJECT_UNINITIALIZED:
4596
      go_unreachable();
4597
 
4598
    case NAMED_OBJECT_ERRONEOUS:
4599
      return Linemap::unknown_location();
4600
 
4601
    case NAMED_OBJECT_UNKNOWN:
4602
      return this->unknown_value()->location();
4603
 
4604
    case NAMED_OBJECT_CONST:
4605
      return this->const_value()->location();
4606
 
4607
    case NAMED_OBJECT_TYPE:
4608
      return this->type_value()->location();
4609
 
4610
    case NAMED_OBJECT_TYPE_DECLARATION:
4611
      return this->type_declaration_value()->location();
4612
 
4613
    case NAMED_OBJECT_VAR:
4614
      return this->var_value()->location();
4615
 
4616
    case NAMED_OBJECT_RESULT_VAR:
4617
      return this->result_var_value()->location();
4618
 
4619
    case NAMED_OBJECT_SINK:
4620
      go_unreachable();
4621
 
4622
    case NAMED_OBJECT_FUNC:
4623
      return this->func_value()->location();
4624
 
4625
    case NAMED_OBJECT_FUNC_DECLARATION:
4626
      return this->func_declaration_value()->location();
4627
 
4628
    case NAMED_OBJECT_PACKAGE:
4629
      return this->package_value()->location();
4630
    }
4631
}
4632
 
4633
// Export a named object.
4634
 
4635
void
4636
Named_object::export_named_object(Export* exp) const
4637
{
4638
  switch (this->classification_)
4639
    {
4640
    default:
4641
    case NAMED_OBJECT_UNINITIALIZED:
4642
    case NAMED_OBJECT_UNKNOWN:
4643
      go_unreachable();
4644
 
4645
    case NAMED_OBJECT_ERRONEOUS:
4646
      break;
4647
 
4648
    case NAMED_OBJECT_CONST:
4649
      this->const_value()->export_const(exp, this->name_);
4650
      break;
4651
 
4652
    case NAMED_OBJECT_TYPE:
4653
      this->type_value()->export_named_type(exp, this->name_);
4654
      break;
4655
 
4656
    case NAMED_OBJECT_TYPE_DECLARATION:
4657
      error_at(this->type_declaration_value()->location(),
4658
               "attempt to export %<%s%> which was declared but not defined",
4659
               this->message_name().c_str());
4660
      break;
4661
 
4662
    case NAMED_OBJECT_FUNC_DECLARATION:
4663
      this->func_declaration_value()->export_func(exp, this->name_);
4664
      break;
4665
 
4666
    case NAMED_OBJECT_VAR:
4667
      this->var_value()->export_var(exp, this->name_);
4668
      break;
4669
 
4670
    case NAMED_OBJECT_RESULT_VAR:
4671
    case NAMED_OBJECT_SINK:
4672
      go_unreachable();
4673
 
4674
    case NAMED_OBJECT_FUNC:
4675
      this->func_value()->export_func(exp, this->name_);
4676
      break;
4677
    }
4678
}
4679
 
4680
// Convert a variable to the backend representation.
4681
 
4682
Bvariable*
4683
Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4684
{
4685
  if (this->classification_ == NAMED_OBJECT_VAR)
4686
    return this->var_value()->get_backend_variable(gogo, function,
4687
                                                   this->package_, this->name_);
4688
  else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4689
    return this->result_var_value()->get_backend_variable(gogo, function,
4690
                                                          this->name_);
4691
  else
4692
    go_unreachable();
4693
}
4694
 
4695
// Class Bindings.
4696
 
4697
Bindings::Bindings(Bindings* enclosing)
4698
  : enclosing_(enclosing), named_objects_(), bindings_()
4699
{
4700
}
4701
 
4702
// Clear imports.
4703
 
4704
void
4705
Bindings::clear_file_scope()
4706
{
4707
  Contour::iterator p = this->bindings_.begin();
4708
  while (p != this->bindings_.end())
4709
    {
4710
      bool keep;
4711
      if (p->second->package() != NULL)
4712
        keep = false;
4713
      else if (p->second->is_package())
4714
        keep = false;
4715
      else if (p->second->is_function()
4716
               && !p->second->func_value()->type()->is_method()
4717
               && Gogo::unpack_hidden_name(p->second->name()) == "init")
4718
        keep = false;
4719
      else
4720
        keep = true;
4721
 
4722
      if (keep)
4723
        ++p;
4724
      else
4725
        p = this->bindings_.erase(p);
4726
    }
4727
}
4728
 
4729
// Look up a symbol.
4730
 
4731
Named_object*
4732
Bindings::lookup(const std::string& name) const
4733
{
4734
  Contour::const_iterator p = this->bindings_.find(name);
4735
  if (p != this->bindings_.end())
4736
    return p->second->resolve();
4737
  else if (this->enclosing_ != NULL)
4738
    return this->enclosing_->lookup(name);
4739
  else
4740
    return NULL;
4741
}
4742
 
4743
// Look up a symbol locally.
4744
 
4745
Named_object*
4746
Bindings::lookup_local(const std::string& name) const
4747
{
4748
  Contour::const_iterator p = this->bindings_.find(name);
4749
  if (p == this->bindings_.end())
4750
    return NULL;
4751
  return p->second;
4752
}
4753
 
4754
// Remove an object from a set of bindings.  This is used for a
4755
// special case in thunks for functions which call recover.
4756
 
4757
void
4758
Bindings::remove_binding(Named_object* no)
4759
{
4760
  Contour::iterator pb = this->bindings_.find(no->name());
4761
  go_assert(pb != this->bindings_.end());
4762
  this->bindings_.erase(pb);
4763
  for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4764
       pn != this->named_objects_.end();
4765
       ++pn)
4766
    {
4767
      if (*pn == no)
4768
        {
4769
          this->named_objects_.erase(pn);
4770
          return;
4771
        }
4772
    }
4773
  go_unreachable();
4774
}
4775
 
4776
// Add a method to the list of objects.  This is not added to the
4777
// lookup table.  This is so that we have a single list of objects
4778
// declared at the top level, which we walk through when it's time to
4779
// convert to trees.
4780
 
4781
void
4782
Bindings::add_method(Named_object* method)
4783
{
4784
  this->named_objects_.push_back(method);
4785
}
4786
 
4787
// Add a generic Named_object to a Contour.
4788
 
4789
Named_object*
4790
Bindings::add_named_object_to_contour(Contour* contour,
4791
                                      Named_object* named_object)
4792
{
4793
  go_assert(named_object == named_object->resolve());
4794
  const std::string& name(named_object->name());
4795
  go_assert(!Gogo::is_sink_name(name));
4796
 
4797
  std::pair<Contour::iterator, bool> ins =
4798
    contour->insert(std::make_pair(name, named_object));
4799
  if (!ins.second)
4800
    {
4801
      // The name was already there.
4802
      if (named_object->package() != NULL
4803
          && ins.first->second->package() == named_object->package()
4804
          && (ins.first->second->classification()
4805
              == named_object->classification()))
4806
        {
4807
          // This is a second import of the same object.
4808
          return ins.first->second;
4809
        }
4810
      ins.first->second = this->new_definition(ins.first->second,
4811
                                               named_object);
4812
      return ins.first->second;
4813
    }
4814
  else
4815
    {
4816
      // Don't push declarations on the list.  We push them on when
4817
      // and if we find the definitions.  That way we genericize the
4818
      // functions in order.
4819
      if (!named_object->is_type_declaration()
4820
          && !named_object->is_function_declaration()
4821
          && !named_object->is_unknown())
4822
        this->named_objects_.push_back(named_object);
4823
      return named_object;
4824
    }
4825
}
4826
 
4827
// We had an existing named object OLD_OBJECT, and we've seen a new
4828
// one NEW_OBJECT with the same name.  FIXME: This does not free the
4829
// new object when we don't need it.
4830
 
4831
Named_object*
4832
Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4833
{
4834
  if (new_object->is_erroneous() && !old_object->is_erroneous())
4835
    return new_object;
4836
 
4837
  std::string reason;
4838
  switch (old_object->classification())
4839
    {
4840
    default:
4841
    case Named_object::NAMED_OBJECT_UNINITIALIZED:
4842
      go_unreachable();
4843
 
4844
    case Named_object::NAMED_OBJECT_ERRONEOUS:
4845
      return old_object;
4846
 
4847
    case Named_object::NAMED_OBJECT_UNKNOWN:
4848
      {
4849
        Named_object* real = old_object->unknown_value()->real_named_object();
4850
        if (real != NULL)
4851
          return this->new_definition(real, new_object);
4852
        go_assert(!new_object->is_unknown());
4853
        old_object->unknown_value()->set_real_named_object(new_object);
4854
        if (!new_object->is_type_declaration()
4855
            && !new_object->is_function_declaration())
4856
          this->named_objects_.push_back(new_object);
4857
        return new_object;
4858
      }
4859
 
4860
    case Named_object::NAMED_OBJECT_CONST:
4861
      break;
4862
 
4863
    case Named_object::NAMED_OBJECT_TYPE:
4864
      if (new_object->is_type_declaration())
4865
        return old_object;
4866
      break;
4867
 
4868
    case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4869
      if (new_object->is_type_declaration())
4870
        return old_object;
4871
      if (new_object->is_type())
4872
        {
4873
          old_object->set_type_value(new_object->type_value());
4874
          new_object->type_value()->set_named_object(old_object);
4875
          this->named_objects_.push_back(old_object);
4876
          return old_object;
4877
        }
4878
      break;
4879
 
4880
    case Named_object::NAMED_OBJECT_VAR:
4881
    case Named_object::NAMED_OBJECT_RESULT_VAR:
4882
      // We have already given an error in the parser for cases where
4883
      // one parameter or result variable redeclares another one.
4884
      if ((new_object->is_variable()
4885
           && new_object->var_value()->is_parameter())
4886
          || new_object->is_result_variable())
4887
        return old_object;
4888
      break;
4889
 
4890
    case Named_object::NAMED_OBJECT_SINK:
4891
      go_unreachable();
4892
 
4893
    case Named_object::NAMED_OBJECT_FUNC:
4894
      if (new_object->is_function_declaration())
4895
        {
4896
          if (!new_object->func_declaration_value()->asm_name().empty())
4897
            sorry("__asm__ for function definitions");
4898
          Function_type* old_type = old_object->func_value()->type();
4899
          Function_type* new_type =
4900
            new_object->func_declaration_value()->type();
4901
          if (old_type->is_valid_redeclaration(new_type, &reason))
4902
            return old_object;
4903
        }
4904
      break;
4905
 
4906
    case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4907
      {
4908
        Function_type* old_type = old_object->func_declaration_value()->type();
4909
        if (new_object->is_function_declaration())
4910
          {
4911
            Function_type* new_type =
4912
              new_object->func_declaration_value()->type();
4913
            if (old_type->is_valid_redeclaration(new_type, &reason))
4914
              return old_object;
4915
          }
4916
        if (new_object->is_function())
4917
          {
4918
            Function_type* new_type = new_object->func_value()->type();
4919
            if (old_type->is_valid_redeclaration(new_type, &reason))
4920
              {
4921
                if (!old_object->func_declaration_value()->asm_name().empty())
4922
                  sorry("__asm__ for function definitions");
4923
                old_object->set_function_value(new_object->func_value());
4924
                this->named_objects_.push_back(old_object);
4925
                return old_object;
4926
              }
4927
          }
4928
      }
4929
      break;
4930
 
4931
    case Named_object::NAMED_OBJECT_PACKAGE:
4932
      if (new_object->is_package()
4933
          && (old_object->package_value()->name()
4934
              == new_object->package_value()->name()))
4935
        return old_object;
4936
 
4937
      break;
4938
    }
4939
 
4940
  std::string n = old_object->message_name();
4941
  if (reason.empty())
4942
    error_at(new_object->location(), "redefinition of %qs", n.c_str());
4943
  else
4944
    error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4945
             reason.c_str());
4946
 
4947
  inform(old_object->location(), "previous definition of %qs was here",
4948
         n.c_str());
4949
 
4950
  return old_object;
4951
}
4952
 
4953
// Add a named type.
4954
 
4955
Named_object*
4956
Bindings::add_named_type(Named_type* named_type)
4957
{
4958
  return this->add_named_object(named_type->named_object());
4959
}
4960
 
4961
// Add a function.
4962
 
4963
Named_object*
4964
Bindings::add_function(const std::string& name, const Package* package,
4965
                       Function* function)
4966
{
4967
  return this->add_named_object(Named_object::make_function(name, package,
4968
                                                            function));
4969
}
4970
 
4971
// Add a function declaration.
4972
 
4973
Named_object*
4974
Bindings::add_function_declaration(const std::string& name,
4975
                                   const Package* package,
4976
                                   Function_type* type,
4977
                                   Location location)
4978
{
4979
  Named_object* no = Named_object::make_function_declaration(name, package,
4980
                                                             type, location);
4981
  return this->add_named_object(no);
4982
}
4983
 
4984
// Define a type which was previously declared.
4985
 
4986
void
4987
Bindings::define_type(Named_object* no, Named_type* type)
4988
{
4989
  no->set_type_value(type);
4990
  this->named_objects_.push_back(no);
4991
}
4992
 
4993
// Mark all local variables as used.  This is used for some types of
4994
// parse error.
4995
 
4996
void
4997
Bindings::mark_locals_used()
4998
{
4999
  for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
5000
       p != this->named_objects_.end();
5001
       ++p)
5002
    if ((*p)->is_variable())
5003
      (*p)->var_value()->set_is_used();
5004
}
5005
 
5006
// Traverse bindings.
5007
 
5008
int
5009
Bindings::traverse(Traverse* traverse, bool is_global)
5010
{
5011
  unsigned int traverse_mask = traverse->traverse_mask();
5012
 
5013
  // We don't use an iterator because we permit the traversal to add
5014
  // new global objects.
5015
  const unsigned int e_or_t = (Traverse::traverse_expressions
5016
                               | Traverse::traverse_types);
5017
  const unsigned int e_or_t_or_s = (e_or_t
5018
                                    | Traverse::traverse_statements);
5019
  for (size_t i = 0; i < this->named_objects_.size(); ++i)
5020
    {
5021
      Named_object* p = this->named_objects_[i];
5022
      int t = TRAVERSE_CONTINUE;
5023
      switch (p->classification())
5024
        {
5025
        case Named_object::NAMED_OBJECT_CONST:
5026
          if ((traverse_mask & Traverse::traverse_constants) != 0)
5027
            t = traverse->constant(p, is_global);
5028
          if (t == TRAVERSE_CONTINUE
5029
              && (traverse_mask & e_or_t) != 0)
5030
            {
5031
              Type* tc = p->const_value()->type();
5032
              if (tc != NULL
5033
                  && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5034
                return TRAVERSE_EXIT;
5035
              t = p->const_value()->traverse_expression(traverse);
5036
            }
5037
          break;
5038
 
5039
        case Named_object::NAMED_OBJECT_VAR:
5040
        case Named_object::NAMED_OBJECT_RESULT_VAR:
5041
          if ((traverse_mask & Traverse::traverse_variables) != 0)
5042
            t = traverse->variable(p);
5043
          if (t == TRAVERSE_CONTINUE
5044
              && (traverse_mask & e_or_t) != 0)
5045
            {
5046
              if (p->is_result_variable()
5047
                  || p->var_value()->has_type())
5048
                {
5049
                  Type* tv = (p->is_variable()
5050
                              ? p->var_value()->type()
5051
                              : p->result_var_value()->type());
5052
                  if (tv != NULL
5053
                      && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5054
                    return TRAVERSE_EXIT;
5055
                }
5056
            }
5057
          if (t == TRAVERSE_CONTINUE
5058
              && (traverse_mask & e_or_t_or_s) != 0
5059
              && p->is_variable())
5060
            t = p->var_value()->traverse_expression(traverse, traverse_mask);
5061
          break;
5062
 
5063
        case Named_object::NAMED_OBJECT_FUNC:
5064
          if ((traverse_mask & Traverse::traverse_functions) != 0)
5065
            t = traverse->function(p);
5066
 
5067
          if (t == TRAVERSE_CONTINUE
5068
              && (traverse_mask
5069
                  & (Traverse::traverse_variables
5070
                     | Traverse::traverse_constants
5071
                     | Traverse::traverse_functions
5072
                     | Traverse::traverse_blocks
5073
                     | Traverse::traverse_statements
5074
                     | Traverse::traverse_expressions
5075
                     | Traverse::traverse_types)) != 0)
5076
            t = p->func_value()->traverse(traverse);
5077
          break;
5078
 
5079
        case Named_object::NAMED_OBJECT_PACKAGE:
5080
          // These are traversed in Gogo::traverse.
5081
          go_assert(is_global);
5082
          break;
5083
 
5084
        case Named_object::NAMED_OBJECT_TYPE:
5085
          if ((traverse_mask & e_or_t) != 0)
5086
            t = Type::traverse(p->type_value(), traverse);
5087
          break;
5088
 
5089
        case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5090
        case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5091
        case Named_object::NAMED_OBJECT_UNKNOWN:
5092
        case Named_object::NAMED_OBJECT_ERRONEOUS:
5093
          break;
5094
 
5095
        case Named_object::NAMED_OBJECT_SINK:
5096
        default:
5097
          go_unreachable();
5098
        }
5099
 
5100
      if (t == TRAVERSE_EXIT)
5101
        return TRAVERSE_EXIT;
5102
    }
5103
 
5104
  // If we need to traverse types, check the function declarations,
5105
  // which have types.  We don't need to check the type declarations,
5106
  // as those are just names.
5107
  if ((traverse_mask & e_or_t) != 0)
5108
    {
5109
      for (Bindings::const_declarations_iterator p =
5110
             this->begin_declarations();
5111
           p != this->end_declarations();
5112
           ++p)
5113
        {
5114
          if (p->second->is_function_declaration())
5115
            {
5116
              if (Type::traverse(p->second->func_declaration_value()->type(),
5117
                                 traverse)
5118
                  == TRAVERSE_EXIT)
5119
                return TRAVERSE_EXIT;
5120
            }
5121
        }
5122
    }
5123
 
5124
  return TRAVERSE_CONTINUE;
5125
}
5126
 
5127
// Class Label.
5128
 
5129
// Clear any references to this label.
5130
 
5131
void
5132
Label::clear_refs()
5133
{
5134
  for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
5135
       p != this->refs_.end();
5136
       ++p)
5137
    delete *p;
5138
  this->refs_.clear();
5139
}
5140
 
5141
// Get the backend representation for a label.
5142
 
5143
Blabel*
5144
Label::get_backend_label(Translate_context* context)
5145
{
5146
  if (this->blabel_ == NULL)
5147
    {
5148
      Function* function = context->function()->func_value();
5149
      tree fndecl = function->get_decl();
5150
      Bfunction* bfunction = tree_to_function(fndecl);
5151
      this->blabel_ = context->backend()->label(bfunction, this->name_,
5152
                                                this->location_);
5153
    }
5154
  return this->blabel_;
5155
}
5156
 
5157
// Return an expression for the address of this label.
5158
 
5159
Bexpression*
5160
Label::get_addr(Translate_context* context, Location location)
5161
{
5162
  Blabel* label = this->get_backend_label(context);
5163
  return context->backend()->label_address(label, location);
5164
}
5165
 
5166
// Class Unnamed_label.
5167
 
5168
// Get the backend representation for an unnamed label.
5169
 
5170
Blabel*
5171
Unnamed_label::get_blabel(Translate_context* context)
5172
{
5173
  if (this->blabel_ == NULL)
5174
    {
5175
      Function* function = context->function()->func_value();
5176
      tree fndecl = function->get_decl();
5177
      Bfunction* bfunction = tree_to_function(fndecl);
5178
      this->blabel_ = context->backend()->label(bfunction, "",
5179
                                                this->location_);
5180
    }
5181
  return this->blabel_;
5182
}
5183
 
5184
// Return a statement which defines this unnamed label.
5185
 
5186
Bstatement*
5187
Unnamed_label::get_definition(Translate_context* context)
5188
{
5189
  Blabel* blabel = this->get_blabel(context);
5190
  return context->backend()->label_definition_statement(blabel);
5191
}
5192
 
5193
// Return a goto statement to this unnamed label.
5194
 
5195
Bstatement*
5196
Unnamed_label::get_goto(Translate_context* context, Location location)
5197
{
5198
  Blabel* blabel = this->get_blabel(context);
5199
  return context->backend()->goto_statement(blabel, location);
5200
}
5201
 
5202
// Class Package.
5203
 
5204
Package::Package(const std::string& name, const std::string& unique_prefix,
5205
                 Location location)
5206
  : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
5207
    priority_(0), location_(location), used_(false), is_imported_(false),
5208
    uses_sink_alias_(false)
5209
{
5210
  go_assert(!name.empty() && !unique_prefix.empty());
5211
}
5212
 
5213
// Set the priority.  We may see multiple priorities for an imported
5214
// package; we want to use the largest one.
5215
 
5216
void
5217
Package::set_priority(int priority)
5218
{
5219
  if (priority > this->priority_)
5220
    this->priority_ = priority;
5221
}
5222
 
5223
// Determine types of constants.  Everything else in a package
5224
// (variables, function declarations) should already have a fixed
5225
// type.  Constants may have abstract types.
5226
 
5227
void
5228
Package::determine_types()
5229
{
5230
  Bindings* bindings = this->bindings_;
5231
  for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5232
       p != bindings->end_definitions();
5233
       ++p)
5234
    {
5235
      if ((*p)->is_const())
5236
        (*p)->const_value()->determine_type();
5237
    }
5238
}
5239
 
5240
// Class Traverse.
5241
 
5242
// Destructor.
5243
 
5244
Traverse::~Traverse()
5245
{
5246
  if (this->types_seen_ != NULL)
5247
    delete this->types_seen_;
5248
  if (this->expressions_seen_ != NULL)
5249
    delete this->expressions_seen_;
5250
}
5251
 
5252
// Record that we are looking at a type, and return true if we have
5253
// already seen it.
5254
 
5255
bool
5256
Traverse::remember_type(const Type* type)
5257
{
5258
  if (type->is_error_type())
5259
    return true;
5260
  go_assert((this->traverse_mask() & traverse_types) != 0
5261
             || (this->traverse_mask() & traverse_expressions) != 0);
5262
  // We mostly only have to remember named types.  But it turns out
5263
  // that an interface type can refer to itself without using a name
5264
  // by relying on interface inheritance, as in
5265
  // type I interface { F() interface{I} }
5266
  if (type->classification() != Type::TYPE_NAMED
5267
      && type->classification() != Type::TYPE_INTERFACE)
5268
    return false;
5269
  if (this->types_seen_ == NULL)
5270
    this->types_seen_ = new Types_seen();
5271
  std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
5272
  return !ins.second;
5273
}
5274
 
5275
// Record that we are looking at an expression, and return true if we
5276
// have already seen it.
5277
 
5278
bool
5279
Traverse::remember_expression(const Expression* expression)
5280
{
5281
  go_assert((this->traverse_mask() & traverse_types) != 0
5282
             || (this->traverse_mask() & traverse_expressions) != 0);
5283
  if (this->expressions_seen_ == NULL)
5284
    this->expressions_seen_ = new Expressions_seen();
5285
  std::pair<Expressions_seen::iterator, bool> ins =
5286
    this->expressions_seen_->insert(expression);
5287
  return !ins.second;
5288
}
5289
 
5290
// The default versions of these functions should never be called: the
5291
// traversal mask indicates which functions may be called.
5292
 
5293
int
5294
Traverse::variable(Named_object*)
5295
{
5296
  go_unreachable();
5297
}
5298
 
5299
int
5300
Traverse::constant(Named_object*, bool)
5301
{
5302
  go_unreachable();
5303
}
5304
 
5305
int
5306
Traverse::function(Named_object*)
5307
{
5308
  go_unreachable();
5309
}
5310
 
5311
int
5312
Traverse::block(Block*)
5313
{
5314
  go_unreachable();
5315
}
5316
 
5317
int
5318
Traverse::statement(Block*, size_t*, Statement*)
5319
{
5320
  go_unreachable();
5321
}
5322
 
5323
int
5324
Traverse::expression(Expression**)
5325
{
5326
  go_unreachable();
5327
}
5328
 
5329
int
5330
Traverse::type(Type*)
5331
{
5332
  go_unreachable();
5333
}
5334
 
5335
// Class Statement_inserter.
5336
 
5337
void
5338
Statement_inserter::insert(Statement* s)
5339
{
5340
  if (this->block_ != NULL)
5341
    {
5342
      go_assert(this->pindex_ != NULL);
5343
      this->block_->insert_statement_before(*this->pindex_, s);
5344
      ++*this->pindex_;
5345
    }
5346
  else if (this->var_ != NULL)
5347
    this->var_->add_preinit_statement(this->gogo_, s);
5348
  else
5349
    go_unreachable();
5350
}

powered by: WebSVN 2.1.0

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