OSDN Git Service

compiler: Give an error if a variable is defined but not used.
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / gogo.cc
1 // 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     interface_types_(),
41     specific_type_functions_(),
42     specific_type_functions_are_written_(false),
43     named_types_are_converted_(false)
44 {
45   const Location loc = Linemap::predeclared_location();
46
47   Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
48                                                    RUNTIME_TYPE_KIND_UINT8);
49   this->add_named_type(uint8_type);
50   this->add_named_type(Type::make_integer_type("uint16", true,  16,
51                                                RUNTIME_TYPE_KIND_UINT16));
52   this->add_named_type(Type::make_integer_type("uint32", true,  32,
53                                                RUNTIME_TYPE_KIND_UINT32));
54   this->add_named_type(Type::make_integer_type("uint64", true,  64,
55                                                RUNTIME_TYPE_KIND_UINT64));
56
57   this->add_named_type(Type::make_integer_type("int8",  false,   8,
58                                                RUNTIME_TYPE_KIND_INT8));
59   this->add_named_type(Type::make_integer_type("int16", false,  16,
60                                                RUNTIME_TYPE_KIND_INT16));
61   Named_type* int32_type = Type::make_integer_type("int32", false,  32,
62                                                    RUNTIME_TYPE_KIND_INT32);
63   this->add_named_type(int32_type);
64   this->add_named_type(Type::make_integer_type("int64", false,  64,
65                                                RUNTIME_TYPE_KIND_INT64));
66
67   this->add_named_type(Type::make_float_type("float32", 32,
68                                              RUNTIME_TYPE_KIND_FLOAT32));
69   this->add_named_type(Type::make_float_type("float64", 64,
70                                              RUNTIME_TYPE_KIND_FLOAT64));
71
72   this->add_named_type(Type::make_complex_type("complex64", 64,
73                                                RUNTIME_TYPE_KIND_COMPLEX64));
74   this->add_named_type(Type::make_complex_type("complex128", 128,
75                                                RUNTIME_TYPE_KIND_COMPLEX128));
76
77   if (int_type_size < 32)
78     int_type_size = 32;
79   this->add_named_type(Type::make_integer_type("uint", true,
80                                                int_type_size,
81                                                RUNTIME_TYPE_KIND_UINT));
82   Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
83                                                  RUNTIME_TYPE_KIND_INT);
84   this->add_named_type(int_type);
85
86   this->add_named_type(Type::make_integer_type("uintptr", true,
87                                                pointer_size,
88                                                RUNTIME_TYPE_KIND_UINTPTR));
89
90   // "byte" is an alias for "uint8".
91   uint8_type->integer_type()->set_is_byte();
92   Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
93                                                     loc);
94   this->add_named_type(byte_type->type_value());
95
96   // "rune" is an alias for "int32".
97   int32_type->integer_type()->set_is_rune();
98   Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
99                                                     loc);
100   this->add_named_type(rune_type->type_value());
101
102   this->add_named_type(Type::make_named_bool_type());
103
104   this->add_named_type(Type::make_named_string_type());
105
106   // "error" is interface { Error() string }.
107   {
108     Typed_identifier_list *methods = new Typed_identifier_list;
109     Typed_identifier_list *results = new Typed_identifier_list;
110     results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
111     Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
112     methods->push_back(Typed_identifier("Error", method_type, loc));
113     Interface_type *error_iface = Type::make_interface_type(methods, loc);
114     error_iface->finalize_methods();
115     Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
116     this->add_named_type(error_type);
117   }
118
119   this->globals_->add_constant(Typed_identifier("true",
120                                                 Type::make_boolean_type(),
121                                                 loc),
122                                NULL,
123                                Expression::make_boolean(true, loc),
124                                0);
125   this->globals_->add_constant(Typed_identifier("false",
126                                                 Type::make_boolean_type(),
127                                                 loc),
128                                NULL,
129                                Expression::make_boolean(false, loc),
130                                0);
131
132   this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
133                                                 loc),
134                                NULL,
135                                Expression::make_nil(loc),
136                                0);
137
138   Type* abstract_int_type = Type::make_abstract_integer_type();
139   this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
140                                                 loc),
141                                NULL,
142                                Expression::make_iota(),
143                                0);
144
145   Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
146   new_type->set_is_varargs();
147   new_type->set_is_builtin();
148   this->globals_->add_function_declaration("new", NULL, new_type, loc);
149
150   Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
151   make_type->set_is_varargs();
152   make_type->set_is_builtin();
153   this->globals_->add_function_declaration("make", NULL, make_type, loc);
154
155   Typed_identifier_list* len_result = new Typed_identifier_list();
156   len_result->push_back(Typed_identifier("", int_type, loc));
157   Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
158                                                      loc);
159   len_type->set_is_builtin();
160   this->globals_->add_function_declaration("len", NULL, len_type, loc);
161
162   Typed_identifier_list* cap_result = new Typed_identifier_list();
163   cap_result->push_back(Typed_identifier("", int_type, loc));
164   Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
165                                                      loc);
166   cap_type->set_is_builtin();
167   this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
168
169   Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
170   print_type->set_is_varargs();
171   print_type->set_is_builtin();
172   this->globals_->add_function_declaration("print", NULL, print_type, loc);
173
174   print_type = Type::make_function_type(NULL, NULL, NULL, loc);
175   print_type->set_is_varargs();
176   print_type->set_is_builtin();
177   this->globals_->add_function_declaration("println", NULL, print_type, loc);
178
179   Type *empty = Type::make_empty_interface_type(loc);
180   Typed_identifier_list* panic_parms = new Typed_identifier_list();
181   panic_parms->push_back(Typed_identifier("e", empty, loc));
182   Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
183                                                        NULL, loc);
184   panic_type->set_is_builtin();
185   this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
186
187   Typed_identifier_list* recover_result = new Typed_identifier_list();
188   recover_result->push_back(Typed_identifier("", empty, loc));
189   Function_type* recover_type = Type::make_function_type(NULL, NULL,
190                                                          recover_result,
191                                                          loc);
192   recover_type->set_is_builtin();
193   this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
194
195   Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
196   close_type->set_is_varargs();
197   close_type->set_is_builtin();
198   this->globals_->add_function_declaration("close", NULL, close_type, loc);
199
200   Typed_identifier_list* copy_result = new Typed_identifier_list();
201   copy_result->push_back(Typed_identifier("", int_type, loc));
202   Function_type* copy_type = Type::make_function_type(NULL, NULL,
203                                                       copy_result, loc);
204   copy_type->set_is_varargs();
205   copy_type->set_is_builtin();
206   this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
207
208   Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
209   append_type->set_is_varargs();
210   append_type->set_is_builtin();
211   this->globals_->add_function_declaration("append", NULL, append_type, loc);
212
213   Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
214   complex_type->set_is_varargs();
215   complex_type->set_is_builtin();
216   this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
217
218   Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
219   real_type->set_is_varargs();
220   real_type->set_is_builtin();
221   this->globals_->add_function_declaration("real", NULL, real_type, loc);
222
223   Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
224   imag_type->set_is_varargs();
225   imag_type->set_is_builtin();
226   this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
227
228   Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
229   delete_type->set_is_varargs();
230   delete_type->set_is_builtin();
231   this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
232 }
233
234 // Munge name for use in an error message.
235
236 std::string
237 Gogo::message_name(const std::string& name)
238 {
239   return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
240 }
241
242 // Get the package name.
243
244 const std::string&
245 Gogo::package_name() const
246 {
247   go_assert(this->package_ != NULL);
248   return this->package_->name();
249 }
250
251 // Set the package name.
252
253 void
254 Gogo::set_package_name(const std::string& package_name,
255                        Location location)
256 {
257   if (this->package_ != NULL && this->package_->name() != package_name)
258     {
259       error_at(location, "expected package %<%s%>",
260                Gogo::message_name(this->package_->name()).c_str());
261       return;
262     }
263
264   // If the user did not specify a unique prefix, we always use "go".
265   // This in effect requires that the package name be unique.
266   if (this->unique_prefix_.empty())
267     this->unique_prefix_ = "go";
268
269   this->package_ = this->register_package(package_name, this->unique_prefix_,
270                                           location);
271
272   // We used to permit people to qualify symbols with the current
273   // package name (e.g., P.x), but we no longer do.
274   // this->globals_->add_package(package_name, this->package_);
275
276   if (this->is_main_package())
277     {
278       // Declare "main" as a function which takes no parameters and
279       // returns no value.
280       Location uloc = Linemap::unknown_location();
281       this->declare_function("main",
282                              Type::make_function_type (NULL, NULL, NULL, uloc),
283                              uloc);
284     }
285 }
286
287 // Return whether this is the "main" package.  This is not true if
288 // -fgo-prefix was used.
289
290 bool
291 Gogo::is_main_package() const
292 {
293   return this->package_name() == "main" && !this->unique_prefix_specified_;
294 }
295
296 // Import a package.
297
298 void
299 Gogo::import_package(const std::string& filename,
300                      const std::string& local_name,
301                      bool is_local_name_exported,
302                      Location location)
303 {
304   if (filename == "unsafe")
305     {
306       this->import_unsafe(local_name, is_local_name_exported, location);
307       return;
308     }
309
310   Imports::const_iterator p = this->imports_.find(filename);
311   if (p != this->imports_.end())
312     {
313       Package* package = p->second;
314       package->set_location(location);
315       package->set_is_imported();
316       std::string ln = local_name;
317       bool is_ln_exported = is_local_name_exported;
318       if (ln.empty())
319         {
320           ln = package->name();
321           is_ln_exported = Lex::is_exported_name(ln);
322         }
323       if (ln == ".")
324         {
325           Bindings* bindings = package->bindings();
326           for (Bindings::const_declarations_iterator p =
327                  bindings->begin_declarations();
328                p != bindings->end_declarations();
329                ++p)
330             this->add_named_object(p->second);
331         }
332       else if (ln == "_")
333         package->set_uses_sink_alias();
334       else
335         {
336           ln = this->pack_hidden_name(ln, is_ln_exported);
337           this->package_->bindings()->add_package(ln, package);
338         }
339       return;
340     }
341
342   Import::Stream* stream = Import::open_package(filename, location);
343   if (stream == NULL)
344     {
345       error_at(location, "import file %qs not found", filename.c_str());
346       return;
347     }
348
349   Import imp(stream, location);
350   imp.register_builtin_types(this);
351   Package* package = imp.import(this, local_name, is_local_name_exported);
352   if (package != NULL)
353     {
354       if (package->name() == this->package_name()
355           && package->unique_prefix() == this->unique_prefix())
356         error_at(location,
357                  ("imported package uses same package name and prefix "
358                   "as package being compiled (see -fgo-prefix option)"));
359
360       this->imports_.insert(std::make_pair(filename, package));
361       package->set_is_imported();
362     }
363
364   delete stream;
365 }
366
367 // Add an import control function for an imported package to the list.
368
369 void
370 Gogo::add_import_init_fn(const std::string& package_name,
371                          const std::string& init_name, int prio)
372 {
373   for (std::set<Import_init>::const_iterator p =
374          this->imported_init_fns_.begin();
375        p != this->imported_init_fns_.end();
376        ++p)
377     {
378       if (p->init_name() == init_name
379           && (p->package_name() != package_name || p->priority() != prio))
380         {
381           error("duplicate package initialization name %qs",
382                 Gogo::message_name(init_name).c_str());
383           inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
384                  Gogo::message_name(p->package_name()).c_str(),
385                  p->priority());
386           inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
387                  Gogo::message_name(package_name).c_str(), prio);
388           return;
389         }
390     }
391
392   this->imported_init_fns_.insert(Import_init(package_name, init_name,
393                                               prio));
394 }
395
396 // Return whether we are at the global binding level.
397
398 bool
399 Gogo::in_global_scope() const
400 {
401   return this->functions_.empty();
402 }
403
404 // Return the current binding contour.
405
406 Bindings*
407 Gogo::current_bindings()
408 {
409   if (!this->functions_.empty())
410     return this->functions_.back().blocks.back()->bindings();
411   else if (this->package_ != NULL)
412     return this->package_->bindings();
413   else
414     return this->globals_;
415 }
416
417 const Bindings*
418 Gogo::current_bindings() const
419 {
420   if (!this->functions_.empty())
421     return this->functions_.back().blocks.back()->bindings();
422   else if (this->package_ != NULL)
423     return this->package_->bindings();
424   else
425     return this->globals_;
426 }
427
428 // Return the current block.
429
430 Block*
431 Gogo::current_block()
432 {
433   if (this->functions_.empty())
434     return NULL;
435   else
436     return this->functions_.back().blocks.back();
437 }
438
439 // Look up a name in the current binding contour.  If PFUNCTION is not
440 // NULL, set it to the function in which the name is defined, or NULL
441 // if the name is defined in global scope.
442
443 Named_object*
444 Gogo::lookup(const std::string& name, Named_object** pfunction) const
445 {
446   if (pfunction != NULL)
447     *pfunction = NULL;
448
449   if (Gogo::is_sink_name(name))
450     return Named_object::make_sink();
451
452   for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
453        p != this->functions_.rend();
454        ++p)
455     {
456       Named_object* ret = p->blocks.back()->bindings()->lookup(name);
457       if (ret != NULL)
458         {
459           if (pfunction != NULL)
460             *pfunction = p->function;
461           return ret;
462         }
463     }
464
465   if (this->package_ != NULL)
466     {
467       Named_object* ret = this->package_->bindings()->lookup(name);
468       if (ret != NULL)
469         {
470           if (ret->package() != NULL)
471             ret->package()->set_used();
472           return ret;
473         }
474     }
475
476   // We do not look in the global namespace.  If we did, the global
477   // namespace would effectively hide names which were defined in
478   // package scope which we have not yet seen.  Instead,
479   // define_global_names is called after parsing is over to connect
480   // undefined names at package scope with names defined at global
481   // scope.
482
483   return NULL;
484 }
485
486 // Look up a name in the current block, without searching enclosing
487 // blocks.
488
489 Named_object*
490 Gogo::lookup_in_block(const std::string& name) const
491 {
492   go_assert(!this->functions_.empty());
493   go_assert(!this->functions_.back().blocks.empty());
494   return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
495 }
496
497 // Look up a name in the global namespace.
498
499 Named_object*
500 Gogo::lookup_global(const char* name) const
501 {
502   return this->globals_->lookup(name);
503 }
504
505 // Add an imported package.
506
507 Package*
508 Gogo::add_imported_package(const std::string& real_name,
509                            const std::string& alias_arg,
510                            bool is_alias_exported,
511                            const std::string& unique_prefix,
512                            Location location,
513                            bool* padd_to_globals)
514 {
515   // FIXME: Now that we compile packages as a whole, should we permit
516   // importing the current package?
517   if (this->package_name() == real_name
518       && this->unique_prefix() == unique_prefix)
519     {
520       *padd_to_globals = false;
521       if (!alias_arg.empty() && alias_arg != ".")
522         {
523           std::string alias = this->pack_hidden_name(alias_arg,
524                                                      is_alias_exported);
525           this->package_->bindings()->add_package(alias, this->package_);
526         }
527       return this->package_;
528     }
529   else if (alias_arg == ".")
530     {
531       *padd_to_globals = true;
532       return this->register_package(real_name, unique_prefix, location);
533     }
534   else if (alias_arg == "_")
535     {
536       Package* ret = this->register_package(real_name, unique_prefix, location);
537       ret->set_uses_sink_alias();
538       return ret;
539     }
540   else
541     {
542       *padd_to_globals = false;
543       std::string alias = alias_arg;
544       if (alias.empty())
545         {
546           alias = real_name;
547           is_alias_exported = Lex::is_exported_name(alias);
548         }
549       alias = this->pack_hidden_name(alias, is_alias_exported);
550       Named_object* no = this->add_package(real_name, alias, unique_prefix,
551                                            location);
552       if (!no->is_package())
553         return NULL;
554       return no->package_value();
555     }
556 }
557
558 // Add a package.
559
560 Named_object*
561 Gogo::add_package(const std::string& real_name, const std::string& alias,
562                   const std::string& unique_prefix, Location location)
563 {
564   go_assert(this->in_global_scope());
565
566   // Register the package.  Note that we might have already seen it in
567   // an earlier import.
568   Package* package = this->register_package(real_name, unique_prefix, location);
569
570   return this->package_->bindings()->add_package(alias, package);
571 }
572
573 // Register a package.  This package may or may not be imported.  This
574 // returns the Package structure for the package, creating if it
575 // necessary.
576
577 Package*
578 Gogo::register_package(const std::string& package_name,
579                        const std::string& unique_prefix,
580                        Location location)
581 {
582   go_assert(!unique_prefix.empty() && !package_name.empty());
583   std::string name = unique_prefix + '.' + package_name;
584   Package* package = NULL;
585   std::pair<Packages::iterator, bool> ins =
586     this->packages_.insert(std::make_pair(name, package));
587   if (!ins.second)
588     {
589       // We have seen this package name before.
590       package = ins.first->second;
591       go_assert(package != NULL);
592       go_assert(package->name() == package_name
593                  && package->unique_prefix() == unique_prefix);
594       if (Linemap::is_unknown_location(package->location()))
595         package->set_location(location);
596     }
597   else
598     {
599       // First time we have seen this package name.
600       package = new Package(package_name, unique_prefix, location);
601       go_assert(ins.first->second == NULL);
602       ins.first->second = package;
603     }
604
605   return package;
606 }
607
608 // Start compiling a function.
609
610 Named_object*
611 Gogo::start_function(const std::string& name, Function_type* type,
612                      bool add_method_to_type, Location location)
613 {
614   bool at_top_level = this->functions_.empty();
615
616   Block* block = new Block(NULL, location);
617
618   Function* enclosing = (at_top_level
619                          ? NULL
620                          : this->functions_.back().function->func_value());
621
622   Function* function = new Function(type, enclosing, block, location);
623
624   if (type->is_method())
625     {
626       const Typed_identifier* receiver = type->receiver();
627       Variable* this_param = new Variable(receiver->type(), NULL, false,
628                                           true, true, location);
629       std::string name = receiver->name();
630       if (name.empty())
631         {
632           // We need to give receivers a name since they wind up in
633           // DECL_ARGUMENTS.  FIXME.
634           static unsigned int count;
635           char buf[50];
636           snprintf(buf, sizeof buf, "r.%u", count);
637           ++count;
638           name = buf;
639         }
640       if (!Gogo::is_sink_name(name))
641         block->bindings()->add_variable(name, NULL, this_param);
642     }
643
644   const Typed_identifier_list* parameters = type->parameters();
645   bool is_varargs = type->is_varargs();
646   if (parameters != NULL)
647     {
648       for (Typed_identifier_list::const_iterator p = parameters->begin();
649            p != parameters->end();
650            ++p)
651         {
652           Variable* param = new Variable(p->type(), NULL, false, true, false,
653                                          location);
654           if (is_varargs && p + 1 == parameters->end())
655             param->set_is_varargs_parameter();
656
657           std::string name = p->name();
658           if (name.empty() || Gogo::is_sink_name(name))
659             {
660               // We need to give parameters a name since they wind up
661               // in DECL_ARGUMENTS.  FIXME.
662               static unsigned int count;
663               char buf[50];
664               snprintf(buf, sizeof buf, "p.%u", count);
665               ++count;
666               name = buf;
667             }
668           block->bindings()->add_variable(name, NULL, param);
669         }
670     }
671
672   function->create_result_variables(this);
673
674   const std::string* pname;
675   std::string nested_name;
676   bool is_init = false;
677   if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
678     {
679       if ((type->parameters() != NULL && !type->parameters()->empty())
680           || (type->results() != NULL && !type->results()->empty()))
681         error_at(location,
682                  "func init must have no arguments and no return values");
683       // There can be multiple "init" functions, so give them each a
684       // different name.
685       static int init_count;
686       char buf[30];
687       snprintf(buf, sizeof buf, ".$init%d", init_count);
688       ++init_count;
689       nested_name = buf;
690       pname = &nested_name;
691       is_init = true;
692     }
693   else if (!name.empty())
694     pname = &name;
695   else
696     {
697       // Invent a name for a nested function.
698       static int nested_count;
699       char buf[30];
700       snprintf(buf, sizeof buf, ".$nested%d", nested_count);
701       ++nested_count;
702       nested_name = buf;
703       pname = &nested_name;
704     }
705
706   Named_object* ret;
707   if (Gogo::is_sink_name(*pname))
708     {
709       static int sink_count;
710       char buf[30];
711       snprintf(buf, sizeof buf, ".$sink%d", sink_count);
712       ++sink_count;
713       ret = Named_object::make_function(buf, NULL, function);
714     }
715   else if (!type->is_method())
716     {
717       ret = this->package_->bindings()->add_function(*pname, NULL, function);
718       if (!ret->is_function() || ret->func_value() != function)
719         {
720           // Redefinition error.  Invent a name to avoid knockon
721           // errors.
722           static int redefinition_count;
723           char buf[30];
724           snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
725           ++redefinition_count;
726           ret = this->package_->bindings()->add_function(buf, NULL, function);
727         }
728     }
729   else
730     {
731       if (!add_method_to_type)
732         ret = Named_object::make_function(name, NULL, function);
733       else
734         {
735           go_assert(at_top_level);
736           Type* rtype = type->receiver()->type();
737
738           // We want to look through the pointer created by the
739           // parser, without getting an error if the type is not yet
740           // defined.
741           if (rtype->classification() == Type::TYPE_POINTER)
742             rtype = rtype->points_to();
743
744           if (rtype->is_error_type())
745             ret = Named_object::make_function(name, NULL, function);
746           else if (rtype->named_type() != NULL)
747             {
748               ret = rtype->named_type()->add_method(name, function);
749               if (!ret->is_function())
750                 {
751                   // Redefinition error.
752                   ret = Named_object::make_function(name, NULL, function);
753                 }
754             }
755           else if (rtype->forward_declaration_type() != NULL)
756             {
757               Named_object* type_no =
758                 rtype->forward_declaration_type()->named_object();
759               if (type_no->is_unknown())
760                 {
761                   // If we are seeing methods it really must be a
762                   // type.  Declare it as such.  An alternative would
763                   // be to support lists of methods for unknown
764                   // expressions.  Either way the error messages if
765                   // this is not a type are going to get confusing.
766                   Named_object* declared =
767                     this->declare_package_type(type_no->name(),
768                                                type_no->location());
769                   go_assert(declared
770                              == type_no->unknown_value()->real_named_object());
771                 }
772               ret = rtype->forward_declaration_type()->add_method(name,
773                                                                   function);
774             }
775           else
776             go_unreachable();
777         }
778       this->package_->bindings()->add_method(ret);
779     }
780
781   this->functions_.resize(this->functions_.size() + 1);
782   Open_function& of(this->functions_.back());
783   of.function = ret;
784   of.blocks.push_back(block);
785
786   if (is_init)
787     {
788       this->init_functions_.push_back(ret);
789       this->need_init_fn_ = true;
790     }
791
792   return ret;
793 }
794
795 // Finish compiling a function.
796
797 void
798 Gogo::finish_function(Location location)
799 {
800   this->finish_block(location);
801   go_assert(this->functions_.back().blocks.empty());
802   this->functions_.pop_back();
803 }
804
805 // Return the current function.
806
807 Named_object*
808 Gogo::current_function() const
809 {
810   go_assert(!this->functions_.empty());
811   return this->functions_.back().function;
812 }
813
814 // Start a new block.
815
816 void
817 Gogo::start_block(Location location)
818 {
819   go_assert(!this->functions_.empty());
820   Block* block = new Block(this->current_block(), location);
821   this->functions_.back().blocks.push_back(block);
822 }
823
824 // Finish a block.
825
826 Block*
827 Gogo::finish_block(Location location)
828 {
829   go_assert(!this->functions_.empty());
830   go_assert(!this->functions_.back().blocks.empty());
831   Block* block = this->functions_.back().blocks.back();
832   this->functions_.back().blocks.pop_back();
833   block->set_end_location(location);
834   return block;
835 }
836
837 // Add an unknown name.
838
839 Named_object*
840 Gogo::add_unknown_name(const std::string& name, Location location)
841 {
842   return this->package_->bindings()->add_unknown_name(name, location);
843 }
844
845 // Declare a function.
846
847 Named_object*
848 Gogo::declare_function(const std::string& name, Function_type* type,
849                        Location location)
850 {
851   if (!type->is_method())
852     return this->current_bindings()->add_function_declaration(name, NULL, type,
853                                                               location);
854   else
855     {
856       // We don't bother to add this to the list of global
857       // declarations.
858       Type* rtype = type->receiver()->type();
859
860       // We want to look through the pointer created by the
861       // parser, without getting an error if the type is not yet
862       // defined.
863       if (rtype->classification() == Type::TYPE_POINTER)
864         rtype = rtype->points_to();
865
866       if (rtype->is_error_type())
867         return NULL;
868       else if (rtype->named_type() != NULL)
869         return rtype->named_type()->add_method_declaration(name, NULL, type,
870                                                            location);
871       else if (rtype->forward_declaration_type() != NULL)
872         {
873           Forward_declaration_type* ftype = rtype->forward_declaration_type();
874           return ftype->add_method_declaration(name, type, location);
875         }
876       else
877         go_unreachable();
878     }
879 }
880
881 // Add a label definition.
882
883 Label*
884 Gogo::add_label_definition(const std::string& label_name,
885                            Location location)
886 {
887   go_assert(!this->functions_.empty());
888   Function* func = this->functions_.back().function->func_value();
889   Label* label = func->add_label_definition(this, label_name, location);
890   this->add_statement(Statement::make_label_statement(label, location));
891   return label;
892 }
893
894 // Add a label reference.
895
896 Label*
897 Gogo::add_label_reference(const std::string& label_name,
898                           Location location, bool issue_goto_errors)
899 {
900   go_assert(!this->functions_.empty());
901   Function* func = this->functions_.back().function->func_value();
902   return func->add_label_reference(this, label_name, location,
903                                    issue_goto_errors);
904 }
905
906 // Return the current binding state.
907
908 Bindings_snapshot*
909 Gogo::bindings_snapshot(Location location)
910 {
911   return new Bindings_snapshot(this->current_block(), location);
912 }
913
914 // Add a statement.
915
916 void
917 Gogo::add_statement(Statement* statement)
918 {
919   go_assert(!this->functions_.empty()
920              && !this->functions_.back().blocks.empty());
921   this->functions_.back().blocks.back()->add_statement(statement);
922 }
923
924 // Add a block.
925
926 void
927 Gogo::add_block(Block* block, Location location)
928 {
929   go_assert(!this->functions_.empty()
930              && !this->functions_.back().blocks.empty());
931   Statement* statement = Statement::make_block_statement(block, location);
932   this->functions_.back().blocks.back()->add_statement(statement);
933 }
934
935 // Add a constant.
936
937 Named_object*
938 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
939                    int iota_value)
940 {
941   return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
942 }
943
944 // Add a type.
945
946 void
947 Gogo::add_type(const std::string& name, Type* type, Location location)
948 {
949   Named_object* no = this->current_bindings()->add_type(name, NULL, type,
950                                                         location);
951   if (!this->in_global_scope() && no->is_type())
952     no->type_value()->set_in_function(this->functions_.back().function);
953 }
954
955 // Add a named type.
956
957 void
958 Gogo::add_named_type(Named_type* type)
959 {
960   go_assert(this->in_global_scope());
961   this->current_bindings()->add_named_type(type);
962 }
963
964 // Declare a type.
965
966 Named_object*
967 Gogo::declare_type(const std::string& name, Location location)
968 {
969   Bindings* bindings = this->current_bindings();
970   Named_object* no = bindings->add_type_declaration(name, NULL, location);
971   if (!this->in_global_scope() && no->is_type_declaration())
972     {
973       Named_object* f = this->functions_.back().function;
974       no->type_declaration_value()->set_in_function(f);
975     }
976   return no;
977 }
978
979 // Declare a type at the package level.
980
981 Named_object*
982 Gogo::declare_package_type(const std::string& name, Location location)
983 {
984   return this->package_->bindings()->add_type_declaration(name, NULL, location);
985 }
986
987 // Declare a function at the package level.
988
989 Named_object*
990 Gogo::declare_package_function(const std::string& name, Function_type* type,
991                                Location location)
992 {
993   return this->package_->bindings()->add_function_declaration(name, NULL, type,
994                                                               location);
995 }
996
997 // Define a type which was already declared.
998
999 void
1000 Gogo::define_type(Named_object* no, Named_type* type)
1001 {
1002   this->current_bindings()->define_type(no, type);
1003 }
1004
1005 // Add a variable.
1006
1007 Named_object*
1008 Gogo::add_variable(const std::string& name, Variable* variable)
1009 {
1010   Named_object* no = this->current_bindings()->add_variable(name, NULL,
1011                                                             variable);
1012
1013   // In a function the middle-end wants to see a DECL_EXPR node.
1014   if (no != NULL
1015       && no->is_variable()
1016       && !no->var_value()->is_parameter()
1017       && !this->functions_.empty())
1018     this->add_statement(Statement::make_variable_declaration(no));
1019
1020   return no;
1021 }
1022
1023 // Add a sink--a reference to the blank identifier _.
1024
1025 Named_object*
1026 Gogo::add_sink()
1027 {
1028   return Named_object::make_sink();
1029 }
1030
1031 // Add a named object.
1032
1033 void
1034 Gogo::add_named_object(Named_object* no)
1035 {
1036   this->current_bindings()->add_named_object(no);
1037 }
1038
1039 // Mark all local variables used.  This is used when some types of
1040 // parse error occur.
1041
1042 void
1043 Gogo::mark_locals_used()
1044 {
1045   for (Open_functions::iterator pf = this->functions_.begin();
1046        pf != this->functions_.end();
1047        ++pf)
1048     {
1049       for (std::vector<Block*>::iterator pb = pf->blocks.begin();
1050            pb != pf->blocks.end();
1051            ++pb)
1052         (*pb)->bindings()->mark_locals_used();
1053     }
1054 }
1055
1056 // Record that we've seen an interface type.
1057
1058 void
1059 Gogo::record_interface_type(Interface_type* itype)
1060 {
1061   this->interface_types_.push_back(itype);
1062 }
1063
1064 // Return a name for a thunk object.
1065
1066 std::string
1067 Gogo::thunk_name()
1068 {
1069   static int thunk_count;
1070   char thunk_name[50];
1071   snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1072   ++thunk_count;
1073   return thunk_name;
1074 }
1075
1076 // Return whether a function is a thunk.
1077
1078 bool
1079 Gogo::is_thunk(const Named_object* no)
1080 {
1081   return no->name().compare(0, 6, "$thunk") == 0;
1082 }
1083
1084 // Define the global names.  We do this only after parsing all the
1085 // input files, because the program might define the global names
1086 // itself.
1087
1088 void
1089 Gogo::define_global_names()
1090 {
1091   for (Bindings::const_declarations_iterator p =
1092          this->globals_->begin_declarations();
1093        p != this->globals_->end_declarations();
1094        ++p)
1095     {
1096       Named_object* global_no = p->second;
1097       std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1098       Named_object* no = this->package_->bindings()->lookup(name);
1099       if (no == NULL)
1100         continue;
1101       no = no->resolve();
1102       if (no->is_type_declaration())
1103         {
1104           if (global_no->is_type())
1105             {
1106               if (no->type_declaration_value()->has_methods())
1107                 error_at(no->location(),
1108                          "may not define methods for global type");
1109               no->set_type_value(global_no->type_value());
1110             }
1111           else
1112             {
1113               error_at(no->location(), "expected type");
1114               Type* errtype = Type::make_error_type();
1115               Named_object* err =
1116                 Named_object::make_type("erroneous_type", NULL, errtype,
1117                                         Linemap::predeclared_location());
1118               no->set_type_value(err->type_value());
1119             }
1120         }
1121       else if (no->is_unknown())
1122         no->unknown_value()->set_real_named_object(global_no);
1123     }
1124 }
1125
1126 // Clear out names in file scope.
1127
1128 void
1129 Gogo::clear_file_scope()
1130 {
1131   this->package_->bindings()->clear_file_scope();
1132
1133   // Warn about packages which were imported but not used.
1134   for (Packages::iterator p = this->packages_.begin();
1135        p != this->packages_.end();
1136        ++p)
1137     {
1138       Package* package = p->second;
1139       if (package != this->package_
1140           && package->is_imported()
1141           && !package->used()
1142           && !package->uses_sink_alias()
1143           && !saw_errors())
1144         error_at(package->location(), "imported and not used: %s",
1145                  Gogo::message_name(package->name()).c_str());
1146       package->clear_is_imported();
1147       package->clear_uses_sink_alias();
1148       package->clear_used();
1149     }
1150 }
1151
1152 // Queue up a type specific function for later writing.  These are
1153 // written out in write_specific_type_functions, called after the
1154 // parse tree is lowered.
1155
1156 void
1157 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1158                                    const std::string& hash_name,
1159                                    Function_type* hash_fntype,
1160                                    const std::string& equal_name,
1161                                    Function_type* equal_fntype)
1162 {
1163   go_assert(!this->specific_type_functions_are_written_);
1164   go_assert(!this->in_global_scope());
1165   Specific_type_function* tsf = new Specific_type_function(type, name,
1166                                                            hash_name,
1167                                                            hash_fntype,
1168                                                            equal_name,
1169                                                            equal_fntype);
1170   this->specific_type_functions_.push_back(tsf);
1171 }
1172
1173 // Look for types which need specific hash or equality functions.
1174
1175 class Specific_type_functions : public Traverse
1176 {
1177  public:
1178   Specific_type_functions(Gogo* gogo)
1179     : Traverse(traverse_types),
1180       gogo_(gogo)
1181   { }
1182
1183   int
1184   type(Type*);
1185
1186  private:
1187   Gogo* gogo_;
1188 };
1189
1190 int
1191 Specific_type_functions::type(Type* t)
1192 {
1193   Named_object* hash_fn;
1194   Named_object* equal_fn;
1195   switch (t->classification())
1196     {
1197     case Type::TYPE_NAMED:
1198       {
1199         if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1200           t->type_functions(this->gogo_, t->named_type(), NULL, NULL, &hash_fn,
1201                             &equal_fn);
1202
1203         // If this is a struct type, we don't want to make functions
1204         // for the unnamed struct.
1205         Type* rt = t->named_type()->real_type();
1206         if (rt->struct_type() == NULL)
1207           {
1208             if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1209               return TRAVERSE_EXIT;
1210           }
1211         else
1212           {
1213             if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1214               return TRAVERSE_EXIT;
1215           }
1216
1217         return TRAVERSE_SKIP_COMPONENTS;
1218       }
1219
1220     case Type::TYPE_STRUCT:
1221     case Type::TYPE_ARRAY:
1222       if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1223         t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1224       break;
1225
1226     default:
1227       break;
1228     }
1229
1230   return TRAVERSE_CONTINUE;
1231 }
1232
1233 // Write out type specific functions.
1234
1235 void
1236 Gogo::write_specific_type_functions()
1237 {
1238   Specific_type_functions stf(this);
1239   this->traverse(&stf);
1240
1241   while (!this->specific_type_functions_.empty())
1242     {
1243       Specific_type_function* tsf = this->specific_type_functions_.back();
1244       this->specific_type_functions_.pop_back();
1245       tsf->type->write_specific_type_functions(this, tsf->name,
1246                                                tsf->hash_name,
1247                                                tsf->hash_fntype,
1248                                                tsf->equal_name,
1249                                                tsf->equal_fntype);
1250       delete tsf;
1251     }
1252   this->specific_type_functions_are_written_ = true;
1253 }
1254
1255 // Traverse the tree.
1256
1257 void
1258 Gogo::traverse(Traverse* traverse)
1259 {
1260   // Traverse the current package first for consistency.  The other
1261   // packages will only contain imported types, constants, and
1262   // declarations.
1263   if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1264     return;
1265   for (Packages::const_iterator p = this->packages_.begin();
1266        p != this->packages_.end();
1267        ++p)
1268     {
1269       if (p->second != this->package_)
1270         {
1271           if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1272             break;
1273         }
1274     }
1275 }
1276
1277 // Traversal class used to verify types.
1278
1279 class Verify_types : public Traverse
1280 {
1281  public:
1282   Verify_types()
1283     : Traverse(traverse_types)
1284   { }
1285
1286   int
1287   type(Type*);
1288 };
1289
1290 // Verify that a type is correct.
1291
1292 int
1293 Verify_types::type(Type* t)
1294 {
1295   if (!t->verify())
1296     return TRAVERSE_SKIP_COMPONENTS;
1297   return TRAVERSE_CONTINUE;
1298 }
1299
1300 // Verify that all types are correct.
1301
1302 void
1303 Gogo::verify_types()
1304 {
1305   Verify_types traverse;
1306   this->traverse(&traverse);
1307 }
1308
1309 // Traversal class used to lower parse tree.
1310
1311 class Lower_parse_tree : public Traverse
1312 {
1313  public:
1314   Lower_parse_tree(Gogo* gogo, Named_object* function)
1315     : Traverse(traverse_variables
1316                | traverse_constants
1317                | traverse_functions
1318                | traverse_statements
1319                | traverse_expressions),
1320       gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1321   { }
1322
1323   void
1324   set_inserter(const Statement_inserter* inserter)
1325   { this->inserter_ = *inserter; }
1326
1327   int
1328   variable(Named_object*);
1329
1330   int
1331   constant(Named_object*, bool);
1332
1333   int
1334   function(Named_object*);
1335
1336   int
1337   statement(Block*, size_t* pindex, Statement*);
1338
1339   int
1340   expression(Expression**);
1341
1342  private:
1343   // General IR.
1344   Gogo* gogo_;
1345   // The function we are traversing.
1346   Named_object* function_;
1347   // Value to use for the predeclared constant iota.
1348   int iota_value_;
1349   // Current statement inserter for use by expressions.
1350   Statement_inserter inserter_;
1351 };
1352
1353 // Lower variables.
1354
1355 int
1356 Lower_parse_tree::variable(Named_object* no)
1357 {
1358   if (!no->is_variable())
1359     return TRAVERSE_CONTINUE;
1360
1361   if (no->is_variable() && no->var_value()->is_global())
1362     {
1363       // Global variables can have loops in their initialization
1364       // expressions.  This is handled in lower_init_expression.
1365       no->var_value()->lower_init_expression(this->gogo_, this->function_,
1366                                              &this->inserter_);
1367       return TRAVERSE_CONTINUE;
1368     }
1369
1370   // This is a local variable.  We are going to return
1371   // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1372   // initialization expression when we reach the variable declaration
1373   // statement.  However, that means that we need to traverse the type
1374   // ourselves.
1375   if (no->var_value()->has_type())
1376     {
1377       Type* type = no->var_value()->type();
1378       if (type != NULL)
1379         {
1380           if (Type::traverse(type, this) == TRAVERSE_EXIT)
1381             return TRAVERSE_EXIT;
1382         }
1383     }
1384   go_assert(!no->var_value()->has_pre_init());
1385
1386   return TRAVERSE_SKIP_COMPONENTS;
1387 }
1388
1389 // Lower constants.  We handle constants specially so that we can set
1390 // the right value for the predeclared constant iota.  This works in
1391 // conjunction with the way we lower Const_expression objects.
1392
1393 int
1394 Lower_parse_tree::constant(Named_object* no, bool)
1395 {
1396   Named_constant* nc = no->const_value();
1397
1398   // Don't get into trouble if the constant's initializer expression
1399   // refers to the constant itself.
1400   if (nc->lowering())
1401     return TRAVERSE_CONTINUE;
1402   nc->set_lowering();
1403
1404   go_assert(this->iota_value_ == -1);
1405   this->iota_value_ = nc->iota_value();
1406   nc->traverse_expression(this);
1407   this->iota_value_ = -1;
1408
1409   nc->clear_lowering();
1410
1411   // We will traverse the expression a second time, but that will be
1412   // fast.
1413
1414   return TRAVERSE_CONTINUE;
1415 }
1416
1417 // Lower function closure types.  Record the function while lowering
1418 // it, so that we can pass it down when lowering an expression.
1419
1420 int
1421 Lower_parse_tree::function(Named_object* no)
1422 {
1423   no->func_value()->set_closure_type();
1424
1425   go_assert(this->function_ == NULL);
1426   this->function_ = no;
1427   int t = no->func_value()->traverse(this);
1428   this->function_ = NULL;
1429
1430   if (t == TRAVERSE_EXIT)
1431     return t;
1432   return TRAVERSE_SKIP_COMPONENTS;
1433 }
1434
1435 // Lower statement parse trees.
1436
1437 int
1438 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1439 {
1440   // Because we explicitly traverse the statement's contents
1441   // ourselves, we want to skip block statements here.  There is
1442   // nothing to lower in a block statement.
1443   if (sorig->is_block_statement())
1444     return TRAVERSE_CONTINUE;
1445
1446   Statement_inserter hold_inserter(this->inserter_);
1447   this->inserter_ = Statement_inserter(block, pindex);
1448
1449   // Lower the expressions first.
1450   int t = sorig->traverse_contents(this);
1451   if (t == TRAVERSE_EXIT)
1452     {
1453       this->inserter_ = hold_inserter;
1454       return t;
1455     }
1456
1457   // Keep lowering until nothing changes.
1458   Statement* s = sorig;
1459   while (true)
1460     {
1461       Statement* snew = s->lower(this->gogo_, this->function_, block,
1462                                  &this->inserter_);
1463       if (snew == s)
1464         break;
1465       s = snew;
1466       t = s->traverse_contents(this);
1467       if (t == TRAVERSE_EXIT)
1468         {
1469           this->inserter_ = hold_inserter;
1470           return t;
1471         }
1472     }
1473
1474   if (s != sorig)
1475     block->replace_statement(*pindex, s);
1476
1477   this->inserter_ = hold_inserter;
1478   return TRAVERSE_SKIP_COMPONENTS;
1479 }
1480
1481 // Lower expression parse trees.
1482
1483 int
1484 Lower_parse_tree::expression(Expression** pexpr)
1485 {
1486   // We have to lower all subexpressions first, so that we can get
1487   // their type if necessary.  This is awkward, because we don't have
1488   // a postorder traversal pass.
1489   if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1490     return TRAVERSE_EXIT;
1491   // Keep lowering until nothing changes.
1492   while (true)
1493     {
1494       Expression* e = *pexpr;
1495       Expression* enew = e->lower(this->gogo_, this->function_,
1496                                   &this->inserter_, this->iota_value_);
1497       if (enew == e)
1498         break;
1499       *pexpr = enew;
1500     }
1501   return TRAVERSE_SKIP_COMPONENTS;
1502 }
1503
1504 // Lower the parse tree.  This is called after the parse is complete,
1505 // when all names should be resolved.
1506
1507 void
1508 Gogo::lower_parse_tree()
1509 {
1510   Lower_parse_tree lower_parse_tree(this, NULL);
1511   this->traverse(&lower_parse_tree);
1512 }
1513
1514 // Lower a block.
1515
1516 void
1517 Gogo::lower_block(Named_object* function, Block* block)
1518 {
1519   Lower_parse_tree lower_parse_tree(this, function);
1520   block->traverse(&lower_parse_tree);
1521 }
1522
1523 // Lower an expression.  INSERTER may be NULL, in which case the
1524 // expression had better not need to create any temporaries.
1525
1526 void
1527 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1528                        Expression** pexpr)
1529 {
1530   Lower_parse_tree lower_parse_tree(this, function);
1531   if (inserter != NULL)
1532     lower_parse_tree.set_inserter(inserter);
1533   lower_parse_tree.expression(pexpr);
1534 }
1535
1536 // Lower a constant.  This is called when lowering a reference to a
1537 // constant.  We have to make sure that the constant has already been
1538 // lowered.
1539
1540 void
1541 Gogo::lower_constant(Named_object* no)
1542 {
1543   go_assert(no->is_const());
1544   Lower_parse_tree lower(this, NULL);
1545   lower.constant(no, false);
1546 }
1547
1548 // Look for interface types to finalize methods of inherited
1549 // interfaces.
1550
1551 class Finalize_methods : public Traverse
1552 {
1553  public:
1554   Finalize_methods(Gogo* gogo)
1555     : Traverse(traverse_types),
1556       gogo_(gogo)
1557   { }
1558
1559   int
1560   type(Type*);
1561
1562  private:
1563   Gogo* gogo_;
1564 };
1565
1566 // Finalize the methods of an interface type.
1567
1568 int
1569 Finalize_methods::type(Type* t)
1570 {
1571   // Check the classification so that we don't finalize the methods
1572   // twice for a named interface type.
1573   switch (t->classification())
1574     {
1575     case Type::TYPE_INTERFACE:
1576       t->interface_type()->finalize_methods();
1577       break;
1578
1579     case Type::TYPE_NAMED:
1580       {
1581         // We have to finalize the methods of the real type first.
1582         // But if the real type is a struct type, then we only want to
1583         // finalize the methods of the field types, not of the struct
1584         // type itself.  We don't want to add methods to the struct,
1585         // since it has a name.
1586         Named_type* nt = t->named_type();
1587         Type* rt = nt->real_type();
1588         if (rt->classification() != Type::TYPE_STRUCT)
1589           {
1590             if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1591               return TRAVERSE_EXIT;
1592           }
1593         else
1594           {
1595             if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1596               return TRAVERSE_EXIT;
1597           }
1598
1599         nt->finalize_methods(this->gogo_);
1600
1601         // If this type is defined in a different package, then finalize the
1602         // types of all the methods, since we won't see them otherwise.
1603         if (nt->named_object()->package() != NULL && nt->has_any_methods())
1604           {
1605             const Methods* methods = nt->methods();
1606             for (Methods::const_iterator p = methods->begin();
1607                  p != methods->end();
1608                  ++p)
1609               {
1610                 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1611                   return TRAVERSE_EXIT;
1612               }
1613           }
1614
1615         return TRAVERSE_SKIP_COMPONENTS;
1616       }
1617
1618     case Type::TYPE_STRUCT:
1619       t->struct_type()->finalize_methods(this->gogo_);
1620       break;
1621
1622     default:
1623       break;
1624     }
1625
1626   return TRAVERSE_CONTINUE;
1627 }
1628
1629 // Finalize method lists and build stub methods for types.
1630
1631 void
1632 Gogo::finalize_methods()
1633 {
1634   Finalize_methods finalize(this);
1635   this->traverse(&finalize);
1636 }
1637
1638 // Set types for unspecified variables and constants.
1639
1640 void
1641 Gogo::determine_types()
1642 {
1643   Bindings* bindings = this->current_bindings();
1644   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1645        p != bindings->end_definitions();
1646        ++p)
1647     {
1648       if ((*p)->is_function())
1649         (*p)->func_value()->determine_types();
1650       else if ((*p)->is_variable())
1651         (*p)->var_value()->determine_type();
1652       else if ((*p)->is_const())
1653         (*p)->const_value()->determine_type();
1654
1655       // See if a variable requires us to build an initialization
1656       // function.  We know that we will see all global variables
1657       // here.
1658       if (!this->need_init_fn_ && (*p)->is_variable())
1659         {
1660           Variable* variable = (*p)->var_value();
1661
1662           // If this is a global variable which requires runtime
1663           // initialization, we need an initialization function.
1664           if (!variable->is_global())
1665             ;
1666           else if (variable->init() == NULL)
1667             ;
1668           else if (variable->type()->interface_type() != NULL)
1669             this->need_init_fn_ = true;
1670           else if (variable->init()->is_constant())
1671             ;
1672           else if (!variable->init()->is_composite_literal())
1673             this->need_init_fn_ = true;
1674           else if (variable->init()->is_nonconstant_composite_literal())
1675             this->need_init_fn_ = true;
1676
1677           // If this is a global variable which holds a pointer value,
1678           // then we need an initialization function to register it as a
1679           // GC root.
1680           if (variable->is_global() && variable->type()->has_pointer())
1681             this->need_init_fn_ = true;
1682         }
1683     }
1684
1685   // Determine the types of constants in packages.
1686   for (Packages::const_iterator p = this->packages_.begin();
1687        p != this->packages_.end();
1688        ++p)
1689     p->second->determine_types();
1690 }
1691
1692 // Traversal class used for type checking.
1693
1694 class Check_types_traverse : public Traverse
1695 {
1696  public:
1697   Check_types_traverse(Gogo* gogo)
1698     : Traverse(traverse_variables
1699                | traverse_constants
1700                | traverse_functions
1701                | traverse_statements
1702                | traverse_expressions),
1703       gogo_(gogo)
1704   { }
1705
1706   int
1707   variable(Named_object*);
1708
1709   int
1710   constant(Named_object*, bool);
1711
1712   int
1713   function(Named_object*);
1714
1715   int
1716   statement(Block*, size_t* pindex, Statement*);
1717
1718   int
1719   expression(Expression**);
1720
1721  private:
1722   // General IR.
1723   Gogo* gogo_;
1724 };
1725
1726 // Check that a variable initializer has the right type.
1727
1728 int
1729 Check_types_traverse::variable(Named_object* named_object)
1730 {
1731   if (named_object->is_variable())
1732     {
1733       Variable* var = named_object->var_value();
1734
1735       // Give error if variable type is not defined.
1736       var->type()->base();
1737
1738       Expression* init = var->init();
1739       std::string reason;
1740       if (init != NULL
1741           && !Type::are_assignable(var->type(), init->type(), &reason))
1742         {
1743           if (reason.empty())
1744             error_at(var->location(), "incompatible type in initialization");
1745           else
1746             error_at(var->location(),
1747                      "incompatible type in initialization (%s)",
1748                      reason.c_str());
1749           var->clear_init();
1750         }
1751       else if (!var->is_used()
1752                && !var->is_global()
1753                && !var->is_parameter()
1754                && !var->is_receiver()
1755                && !var->type()->is_error()
1756                && (init == NULL || !init->is_error_expression())
1757                && !Lex::is_invalid_identifier(named_object->name()))
1758         error_at(var->location(), "%qs declared and not used",
1759                  named_object->message_name().c_str());
1760     }
1761   return TRAVERSE_CONTINUE;
1762 }
1763
1764 // Check that a constant initializer has the right type.
1765
1766 int
1767 Check_types_traverse::constant(Named_object* named_object, bool)
1768 {
1769   Named_constant* constant = named_object->const_value();
1770   Type* ctype = constant->type();
1771   if (ctype->integer_type() == NULL
1772       && ctype->float_type() == NULL
1773       && ctype->complex_type() == NULL
1774       && !ctype->is_boolean_type()
1775       && !ctype->is_string_type())
1776     {
1777       if (ctype->is_nil_type())
1778         error_at(constant->location(), "const initializer cannot be nil");
1779       else if (!ctype->is_error())
1780         error_at(constant->location(), "invalid constant type");
1781       constant->set_error();
1782     }
1783   else if (!constant->expr()->is_constant())
1784     {
1785       error_at(constant->expr()->location(), "expression is not constant");
1786       constant->set_error();
1787     }
1788   else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1789                                  NULL))
1790     {
1791       error_at(constant->location(),
1792                "initialization expression has wrong type");
1793       constant->set_error();
1794     }
1795   return TRAVERSE_CONTINUE;
1796 }
1797
1798 // There are no types to check in a function, but this is where we
1799 // issue warnings about labels which are defined but not referenced.
1800
1801 int
1802 Check_types_traverse::function(Named_object* no)
1803 {
1804   no->func_value()->check_labels();
1805   return TRAVERSE_CONTINUE;
1806 }
1807
1808 // Check that types are valid in a statement.
1809
1810 int
1811 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1812 {
1813   s->check_types(this->gogo_);
1814   return TRAVERSE_CONTINUE;
1815 }
1816
1817 // Check that types are valid in an expression.
1818
1819 int
1820 Check_types_traverse::expression(Expression** expr)
1821 {
1822   (*expr)->check_types(this->gogo_);
1823   return TRAVERSE_CONTINUE;
1824 }
1825
1826 // Check that types are valid.
1827
1828 void
1829 Gogo::check_types()
1830 {
1831   Check_types_traverse traverse(this);
1832   this->traverse(&traverse);
1833 }
1834
1835 // Check the types in a single block.
1836
1837 void
1838 Gogo::check_types_in_block(Block* block)
1839 {
1840   Check_types_traverse traverse(this);
1841   block->traverse(&traverse);
1842 }
1843
1844 // A traversal class used to find a single shortcut operator within an
1845 // expression.
1846
1847 class Find_shortcut : public Traverse
1848 {
1849  public:
1850   Find_shortcut()
1851     : Traverse(traverse_blocks
1852                | traverse_statements
1853                | traverse_expressions),
1854       found_(NULL)
1855   { }
1856
1857   // A pointer to the expression which was found, or NULL if none was
1858   // found.
1859   Expression**
1860   found() const
1861   { return this->found_; }
1862
1863  protected:
1864   int
1865   block(Block*)
1866   { return TRAVERSE_SKIP_COMPONENTS; }
1867
1868   int
1869   statement(Block*, size_t*, Statement*)
1870   { return TRAVERSE_SKIP_COMPONENTS; }
1871
1872   int
1873   expression(Expression**);
1874
1875  private:
1876   Expression** found_;
1877 };
1878
1879 // Find a shortcut expression.
1880
1881 int
1882 Find_shortcut::expression(Expression** pexpr)
1883 {
1884   Expression* expr = *pexpr;
1885   Binary_expression* be = expr->binary_expression();
1886   if (be == NULL)
1887     return TRAVERSE_CONTINUE;
1888   Operator op = be->op();
1889   if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1890     return TRAVERSE_CONTINUE;
1891   go_assert(this->found_ == NULL);
1892   this->found_ = pexpr;
1893   return TRAVERSE_EXIT;
1894 }
1895
1896 // A traversal class used to turn shortcut operators into explicit if
1897 // statements.
1898
1899 class Shortcuts : public Traverse
1900 {
1901  public:
1902   Shortcuts(Gogo* gogo)
1903     : Traverse(traverse_variables
1904                | traverse_statements),
1905       gogo_(gogo)
1906   { }
1907
1908  protected:
1909   int
1910   variable(Named_object*);
1911
1912   int
1913   statement(Block*, size_t*, Statement*);
1914
1915  private:
1916   // Convert a shortcut operator.
1917   Statement*
1918   convert_shortcut(Block* enclosing, Expression** pshortcut);
1919
1920   // The IR.
1921   Gogo* gogo_;
1922 };
1923
1924 // Remove shortcut operators in a single statement.
1925
1926 int
1927 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1928 {
1929   // FIXME: This approach doesn't work for switch statements, because
1930   // we add the new statements before the whole switch when we need to
1931   // instead add them just before the switch expression.  The right
1932   // fix is probably to lower switch statements with nonconstant cases
1933   // to a series of conditionals.
1934   if (s->switch_statement() != NULL)
1935     return TRAVERSE_CONTINUE;
1936
1937   while (true)
1938     {
1939       Find_shortcut find_shortcut;
1940
1941       // If S is a variable declaration, then ordinary traversal won't
1942       // do anything.  We want to explicitly traverse the
1943       // initialization expression if there is one.
1944       Variable_declaration_statement* vds = s->variable_declaration_statement();
1945       Expression* init = NULL;
1946       if (vds == NULL)
1947         s->traverse_contents(&find_shortcut);
1948       else
1949         {
1950           init = vds->var()->var_value()->init();
1951           if (init == NULL)
1952             return TRAVERSE_CONTINUE;
1953           init->traverse(&init, &find_shortcut);
1954         }
1955       Expression** pshortcut = find_shortcut.found();
1956       if (pshortcut == NULL)
1957         return TRAVERSE_CONTINUE;
1958
1959       Statement* snew = this->convert_shortcut(block, pshortcut);
1960       block->insert_statement_before(*pindex, snew);
1961       ++*pindex;
1962
1963       if (pshortcut == &init)
1964         vds->var()->var_value()->set_init(init);
1965     }
1966 }
1967
1968 // Remove shortcut operators in the initializer of a global variable.
1969
1970 int
1971 Shortcuts::variable(Named_object* no)
1972 {
1973   if (no->is_result_variable())
1974     return TRAVERSE_CONTINUE;
1975   Variable* var = no->var_value();
1976   Expression* init = var->init();
1977   if (!var->is_global() || init == NULL)
1978     return TRAVERSE_CONTINUE;
1979
1980   while (true)
1981     {
1982       Find_shortcut find_shortcut;
1983       init->traverse(&init, &find_shortcut);
1984       Expression** pshortcut = find_shortcut.found();
1985       if (pshortcut == NULL)
1986         return TRAVERSE_CONTINUE;
1987
1988       Statement* snew = this->convert_shortcut(NULL, pshortcut);
1989       var->add_preinit_statement(this->gogo_, snew);
1990       if (pshortcut == &init)
1991         var->set_init(init);
1992     }
1993 }
1994
1995 // Given an expression which uses a shortcut operator, return a
1996 // statement which implements it, and update *PSHORTCUT accordingly.
1997
1998 Statement*
1999 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2000 {
2001   Binary_expression* shortcut = (*pshortcut)->binary_expression();
2002   Expression* left = shortcut->left();
2003   Expression* right = shortcut->right();
2004   Location loc = shortcut->location();
2005
2006   Block* retblock = new Block(enclosing, loc);
2007   retblock->set_end_location(loc);
2008
2009   Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
2010                                                       left, loc);
2011   retblock->add_statement(ts);
2012
2013   Block* block = new Block(retblock, loc);
2014   block->set_end_location(loc);
2015   Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2016   Statement* assign = Statement::make_assignment(tmpref, right, loc);
2017   block->add_statement(assign);
2018
2019   Expression* cond = Expression::make_temporary_reference(ts, loc);
2020   if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2021     cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2022
2023   Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2024                                                          loc);
2025   retblock->add_statement(if_statement);
2026
2027   *pshortcut = Expression::make_temporary_reference(ts, loc);
2028
2029   delete shortcut;
2030
2031   // Now convert any shortcut operators in LEFT and RIGHT.
2032   Shortcuts shortcuts(this->gogo_);
2033   retblock->traverse(&shortcuts);
2034
2035   return Statement::make_block_statement(retblock, loc);
2036 }
2037
2038 // Turn shortcut operators into explicit if statements.  Doing this
2039 // considerably simplifies the order of evaluation rules.
2040
2041 void
2042 Gogo::remove_shortcuts()
2043 {
2044   Shortcuts shortcuts(this);
2045   this->traverse(&shortcuts);
2046 }
2047
2048 // A traversal class which finds all the expressions which must be
2049 // evaluated in order within a statement or larger expression.  This
2050 // is used to implement the rules about order of evaluation.
2051
2052 class Find_eval_ordering : public Traverse
2053 {
2054  private:
2055   typedef std::vector<Expression**> Expression_pointers;
2056
2057  public:
2058   Find_eval_ordering()
2059     : Traverse(traverse_blocks
2060                | traverse_statements
2061                | traverse_expressions),
2062       exprs_()
2063   { }
2064
2065   size_t
2066   size() const
2067   { return this->exprs_.size(); }
2068
2069   typedef Expression_pointers::const_iterator const_iterator;
2070
2071   const_iterator
2072   begin() const
2073   { return this->exprs_.begin(); }
2074
2075   const_iterator
2076   end() const
2077   { return this->exprs_.end(); }
2078
2079  protected:
2080   int
2081   block(Block*)
2082   { return TRAVERSE_SKIP_COMPONENTS; }
2083
2084   int
2085   statement(Block*, size_t*, Statement*)
2086   { return TRAVERSE_SKIP_COMPONENTS; }
2087
2088   int
2089   expression(Expression**);
2090
2091  private:
2092   // A list of pointers to expressions with side-effects.
2093   Expression_pointers exprs_;
2094 };
2095
2096 // If an expression must be evaluated in order, put it on the list.
2097
2098 int
2099 Find_eval_ordering::expression(Expression** expression_pointer)
2100 {
2101   // We have to look at subexpressions before this one.
2102   if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2103     return TRAVERSE_EXIT;
2104   if ((*expression_pointer)->must_eval_in_order())
2105     this->exprs_.push_back(expression_pointer);
2106   return TRAVERSE_SKIP_COMPONENTS;
2107 }
2108
2109 // A traversal class for ordering evaluations.
2110
2111 class Order_eval : public Traverse
2112 {
2113  public:
2114   Order_eval(Gogo* gogo)
2115     : Traverse(traverse_variables
2116                | traverse_statements),
2117       gogo_(gogo)
2118   { }
2119
2120   int
2121   variable(Named_object*);
2122
2123   int
2124   statement(Block*, size_t*, Statement*);
2125
2126  private:
2127   // The IR.
2128   Gogo* gogo_;
2129 };
2130
2131 // Implement the order of evaluation rules for a statement.
2132
2133 int
2134 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2135 {
2136   // FIXME: This approach doesn't work for switch statements, because
2137   // we add the new statements before the whole switch when we need to
2138   // instead add them just before the switch expression.  The right
2139   // fix is probably to lower switch statements with nonconstant cases
2140   // to a series of conditionals.
2141   if (s->switch_statement() != NULL)
2142     return TRAVERSE_CONTINUE;
2143
2144   Find_eval_ordering find_eval_ordering;
2145
2146   // If S is a variable declaration, then ordinary traversal won't do
2147   // anything.  We want to explicitly traverse the initialization
2148   // expression if there is one.
2149   Variable_declaration_statement* vds = s->variable_declaration_statement();
2150   Expression* init = NULL;
2151   Expression* orig_init = NULL;
2152   if (vds == NULL)
2153     s->traverse_contents(&find_eval_ordering);
2154   else
2155     {
2156       init = vds->var()->var_value()->init();
2157       if (init == NULL)
2158         return TRAVERSE_CONTINUE;
2159       orig_init = init;
2160
2161       // It might seem that this could be
2162       // init->traverse_subexpressions.  Unfortunately that can fail
2163       // in a case like
2164       //   var err os.Error
2165       //   newvar, err := call(arg())
2166       // Here newvar will have an init of call result 0 of
2167       // call(arg()).  If we only traverse subexpressions, we will
2168       // only find arg(), and we won't bother to move anything out.
2169       // Then we get to the assignment to err, we will traverse the
2170       // whole statement, and this time we will find both call() and
2171       // arg(), and so we will move them out.  This will cause them to
2172       // be put into temporary variables before the assignment to err
2173       // but after the declaration of newvar.  To avoid that problem,
2174       // we traverse the entire expression here.
2175       Expression::traverse(&init, &find_eval_ordering);
2176     }
2177
2178   if (find_eval_ordering.size() <= 1)
2179     {
2180       // If there is only one expression with a side-effect, we can
2181       // leave it in place.
2182       return TRAVERSE_CONTINUE;
2183     }
2184
2185   bool is_thunk = s->thunk_statement() != NULL;
2186   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2187        p != find_eval_ordering.end();
2188        ++p)
2189     {
2190       Expression** pexpr = *p;
2191
2192       // The last expression in a thunk will be the call passed to go
2193       // or defer, which we must not evaluate early.
2194       if (is_thunk && p + 1 == find_eval_ordering.end())
2195         break;
2196
2197       Location loc = (*pexpr)->location();
2198       Statement* s;
2199       if ((*pexpr)->call_expression() == NULL
2200           || (*pexpr)->call_expression()->result_count() < 2)
2201         {
2202           Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2203                                                               loc);
2204           s = ts;
2205           *pexpr = Expression::make_temporary_reference(ts, loc);
2206         }
2207       else
2208         {
2209           // A call expression which returns multiple results needs to
2210           // be handled specially.  We can't create a temporary
2211           // because there is no type to give it.  Any actual uses of
2212           // the values will be done via Call_result_expressions.
2213           s = Statement::make_statement(*pexpr, true);
2214         }
2215
2216       block->insert_statement_before(*pindex, s);
2217       ++*pindex;
2218     }
2219
2220   if (init != orig_init)
2221     vds->var()->var_value()->set_init(init);
2222
2223   return TRAVERSE_CONTINUE;
2224 }
2225
2226 // Implement the order of evaluation rules for the initializer of a
2227 // global variable.
2228
2229 int
2230 Order_eval::variable(Named_object* no)
2231 {
2232   if (no->is_result_variable())
2233     return TRAVERSE_CONTINUE;
2234   Variable* var = no->var_value();
2235   Expression* init = var->init();
2236   if (!var->is_global() || init == NULL)
2237     return TRAVERSE_CONTINUE;
2238
2239   Find_eval_ordering find_eval_ordering;
2240   Expression::traverse(&init, &find_eval_ordering);
2241
2242   if (find_eval_ordering.size() <= 1)
2243     {
2244       // If there is only one expression with a side-effect, we can
2245       // leave it in place.
2246       return TRAVERSE_SKIP_COMPONENTS;
2247     }
2248
2249   Expression* orig_init = init;
2250
2251   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2252        p != find_eval_ordering.end();
2253        ++p)
2254     {
2255       Expression** pexpr = *p;
2256       Location loc = (*pexpr)->location();
2257       Statement* s;
2258       if ((*pexpr)->call_expression() == NULL
2259           || (*pexpr)->call_expression()->result_count() < 2)
2260         {
2261           Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2262                                                               loc);
2263           s = ts;
2264           *pexpr = Expression::make_temporary_reference(ts, loc);
2265         }
2266       else
2267         {
2268           // A call expression which returns multiple results needs to
2269           // be handled specially.
2270           s = Statement::make_statement(*pexpr, true);
2271         }
2272       var->add_preinit_statement(this->gogo_, s);
2273     }
2274
2275   if (init != orig_init)
2276     var->set_init(init);
2277
2278   return TRAVERSE_SKIP_COMPONENTS;
2279 }
2280
2281 // Use temporary variables to implement the order of evaluation rules.
2282
2283 void
2284 Gogo::order_evaluations()
2285 {
2286   Order_eval order_eval(this);
2287   this->traverse(&order_eval);
2288 }
2289
2290 // Traversal to convert calls to the predeclared recover function to
2291 // pass in an argument indicating whether it can recover from a panic
2292 // or not.
2293
2294 class Convert_recover : public Traverse
2295 {
2296  public:
2297   Convert_recover(Named_object* arg)
2298     : Traverse(traverse_expressions),
2299       arg_(arg)
2300   { }
2301
2302  protected:
2303   int
2304   expression(Expression**);
2305
2306  private:
2307   // The argument to pass to the function.
2308   Named_object* arg_;
2309 };
2310
2311 // Convert calls to recover.
2312
2313 int
2314 Convert_recover::expression(Expression** pp)
2315 {
2316   Call_expression* ce = (*pp)->call_expression();
2317   if (ce != NULL && ce->is_recover_call())
2318     ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2319                                                        ce->location()));
2320   return TRAVERSE_CONTINUE;
2321 }
2322
2323 // Traversal for build_recover_thunks.
2324
2325 class Build_recover_thunks : public Traverse
2326 {
2327  public:
2328   Build_recover_thunks(Gogo* gogo)
2329     : Traverse(traverse_functions),
2330       gogo_(gogo)
2331   { }
2332
2333   int
2334   function(Named_object*);
2335
2336  private:
2337   Expression*
2338   can_recover_arg(Location);
2339
2340   // General IR.
2341   Gogo* gogo_;
2342 };
2343
2344 // If this function calls recover, turn it into a thunk.
2345
2346 int
2347 Build_recover_thunks::function(Named_object* orig_no)
2348 {
2349   Function* orig_func = orig_no->func_value();
2350   if (!orig_func->calls_recover()
2351       || orig_func->is_recover_thunk()
2352       || orig_func->has_recover_thunk())
2353     return TRAVERSE_CONTINUE;
2354
2355   Gogo* gogo = this->gogo_;
2356   Location location = orig_func->location();
2357
2358   static int count;
2359   char buf[50];
2360
2361   Function_type* orig_fntype = orig_func->type();
2362   Typed_identifier_list* new_params = new Typed_identifier_list();
2363   std::string receiver_name;
2364   if (orig_fntype->is_method())
2365     {
2366       const Typed_identifier* receiver = orig_fntype->receiver();
2367       snprintf(buf, sizeof buf, "rt.%u", count);
2368       ++count;
2369       receiver_name = buf;
2370       new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2371                                              receiver->location()));
2372     }
2373   const Typed_identifier_list* orig_params = orig_fntype->parameters();
2374   if (orig_params != NULL && !orig_params->empty())
2375     {
2376       for (Typed_identifier_list::const_iterator p = orig_params->begin();
2377            p != orig_params->end();
2378            ++p)
2379         {
2380           snprintf(buf, sizeof buf, "pt.%u", count);
2381           ++count;
2382           new_params->push_back(Typed_identifier(buf, p->type(),
2383                                                  p->location()));
2384         }
2385     }
2386   snprintf(buf, sizeof buf, "pr.%u", count);
2387   ++count;
2388   std::string can_recover_name = buf;
2389   new_params->push_back(Typed_identifier(can_recover_name,
2390                                          Type::lookup_bool_type(),
2391                                          orig_fntype->location()));
2392
2393   const Typed_identifier_list* orig_results = orig_fntype->results();
2394   Typed_identifier_list* new_results;
2395   if (orig_results == NULL || orig_results->empty())
2396     new_results = NULL;
2397   else
2398     {
2399       new_results = new Typed_identifier_list();
2400       for (Typed_identifier_list::const_iterator p = orig_results->begin();
2401            p != orig_results->end();
2402            ++p)
2403         new_results->push_back(Typed_identifier("", p->type(), p->location()));
2404     }
2405
2406   Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2407                                                        new_results,
2408                                                        orig_fntype->location());
2409   if (orig_fntype->is_varargs())
2410     new_fntype->set_is_varargs();
2411
2412   std::string name = orig_no->name() + "$recover";
2413   Named_object *new_no = gogo->start_function(name, new_fntype, false,
2414                                               location);
2415   Function *new_func = new_no->func_value();
2416   if (orig_func->enclosing() != NULL)
2417     new_func->set_enclosing(orig_func->enclosing());
2418
2419   // We build the code for the original function attached to the new
2420   // function, and then swap the original and new function bodies.
2421   // This means that existing references to the original function will
2422   // then refer to the new function.  That makes this code a little
2423   // confusing, in that the reference to NEW_NO really refers to the
2424   // other function, not the one we are building.
2425
2426   Expression* closure = NULL;
2427   if (orig_func->needs_closure())
2428     {
2429       Named_object* orig_closure_no = orig_func->closure_var();
2430       Variable* orig_closure_var = orig_closure_no->var_value();
2431       Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2432                                        true, false, location);
2433       snprintf(buf, sizeof buf, "closure.%u", count);
2434       ++count;
2435       Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2436                                                                  new_var);
2437       new_func->set_closure_var(new_closure_no);
2438       closure = Expression::make_var_reference(new_closure_no, location);
2439     }
2440
2441   Expression* fn = Expression::make_func_reference(new_no, closure, location);
2442
2443   Expression_list* args = new Expression_list();
2444   if (new_params != NULL)
2445     {
2446       // Note that we skip the last parameter, which is the boolean
2447       // indicating whether recover can succed.
2448       for (Typed_identifier_list::const_iterator p = new_params->begin();
2449            p + 1 != new_params->end();
2450            ++p)
2451         {
2452           Named_object* p_no = gogo->lookup(p->name(), NULL);
2453           go_assert(p_no != NULL
2454                      && p_no->is_variable()
2455                      && p_no->var_value()->is_parameter());
2456           args->push_back(Expression::make_var_reference(p_no, location));
2457         }
2458     }
2459   args->push_back(this->can_recover_arg(location));
2460
2461   gogo->start_block(location);
2462
2463   Call_expression* call = Expression::make_call(fn, args, false, location);
2464
2465   Statement* s;
2466   if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2467     s = Statement::make_statement(call, true);
2468   else
2469     {
2470       Expression_list* vals = new Expression_list();
2471       size_t rc = orig_fntype->results()->size();
2472       if (rc == 1)
2473         vals->push_back(call);
2474       else
2475         {
2476           for (size_t i = 0; i < rc; ++i)
2477             vals->push_back(Expression::make_call_result(call, i));
2478         }
2479       s = Statement::make_return_statement(vals, location);
2480     }
2481   s->determine_types();
2482   gogo->add_statement(s);
2483
2484   Block* b = gogo->finish_block(location);
2485
2486   gogo->add_block(b, location);
2487
2488   // Lower the call in case it returns multiple results.
2489   gogo->lower_block(new_no, b);
2490
2491   gogo->finish_function(location);
2492
2493   // Swap the function bodies and types.
2494   new_func->swap_for_recover(orig_func);
2495   orig_func->set_is_recover_thunk();
2496   new_func->set_calls_recover();
2497   new_func->set_has_recover_thunk();
2498
2499   Bindings* orig_bindings = orig_func->block()->bindings();
2500   Bindings* new_bindings = new_func->block()->bindings();
2501   if (orig_fntype->is_method())
2502     {
2503       // We changed the receiver to be a regular parameter.  We have
2504       // to update the binding accordingly in both functions.
2505       Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2506       go_assert(orig_rec_no != NULL
2507                  && orig_rec_no->is_variable()
2508                  && !orig_rec_no->var_value()->is_receiver());
2509       orig_rec_no->var_value()->set_is_receiver();
2510
2511       const std::string& new_receiver_name(orig_fntype->receiver()->name());
2512       Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2513       if (new_rec_no == NULL)
2514         go_assert(saw_errors());
2515       else
2516         {
2517           go_assert(new_rec_no->is_variable()
2518                      && new_rec_no->var_value()->is_receiver());
2519           new_rec_no->var_value()->set_is_not_receiver();
2520         }
2521     }
2522
2523   // Because we flipped blocks but not types, the can_recover
2524   // parameter appears in the (now) old bindings as a parameter.
2525   // Change it to a local variable, whereupon it will be discarded.
2526   Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2527   go_assert(can_recover_no != NULL
2528              && can_recover_no->is_variable()
2529              && can_recover_no->var_value()->is_parameter());
2530   orig_bindings->remove_binding(can_recover_no);
2531
2532   // Add the can_recover argument to the (now) new bindings, and
2533   // attach it to any recover statements.
2534   Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2535                                            false, true, false, location);
2536   can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2537                                               can_recover_var);
2538   Convert_recover convert_recover(can_recover_no);
2539   new_func->traverse(&convert_recover);
2540
2541   // Update the function pointers in any named results.
2542   new_func->update_result_variables();
2543   orig_func->update_result_variables();
2544
2545   return TRAVERSE_CONTINUE;
2546 }
2547
2548 // Return the expression to pass for the .can_recover parameter to the
2549 // new function.  This indicates whether a call to recover may return
2550 // non-nil.  The expression is
2551 // __go_can_recover(__builtin_return_address()).
2552
2553 Expression*
2554 Build_recover_thunks::can_recover_arg(Location location)
2555 {
2556   static Named_object* builtin_return_address;
2557   if (builtin_return_address == NULL)
2558     {
2559       const Location bloc = Linemap::predeclared_location();
2560
2561       Typed_identifier_list* param_types = new Typed_identifier_list();
2562       Type* uint_type = Type::lookup_integer_type("uint");
2563       param_types->push_back(Typed_identifier("l", uint_type, bloc));
2564
2565       Typed_identifier_list* return_types = new Typed_identifier_list();
2566       Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2567       return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2568
2569       Function_type* fntype = Type::make_function_type(NULL, param_types,
2570                                                        return_types, bloc);
2571       builtin_return_address =
2572         Named_object::make_function_declaration("__builtin_return_address",
2573                                                 NULL, fntype, bloc);
2574       const char* n = "__builtin_return_address";
2575       builtin_return_address->func_declaration_value()->set_asm_name(n);
2576     }
2577
2578   static Named_object* can_recover;
2579   if (can_recover == NULL)
2580     {
2581       const Location bloc = Linemap::predeclared_location();
2582       Typed_identifier_list* param_types = new Typed_identifier_list();
2583       Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2584       param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2585       Type* boolean_type = Type::lookup_bool_type();
2586       Typed_identifier_list* results = new Typed_identifier_list();
2587       results->push_back(Typed_identifier("", boolean_type, bloc));
2588       Function_type* fntype = Type::make_function_type(NULL, param_types,
2589                                                        results, bloc);
2590       can_recover = Named_object::make_function_declaration("__go_can_recover",
2591                                                             NULL, fntype,
2592                                                             bloc);
2593       can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2594     }
2595
2596   Expression* fn = Expression::make_func_reference(builtin_return_address,
2597                                                    NULL, location);
2598
2599   mpz_t zval;
2600   mpz_init_set_ui(zval, 0UL);
2601   Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2602   mpz_clear(zval);
2603   Expression_list *args = new Expression_list();
2604   args->push_back(zexpr);
2605
2606   Expression* call = Expression::make_call(fn, args, false, location);
2607
2608   args = new Expression_list();
2609   args->push_back(call);
2610
2611   fn = Expression::make_func_reference(can_recover, NULL, location);
2612   return Expression::make_call(fn, args, false, location);
2613 }
2614
2615 // Build thunks for functions which call recover.  We build a new
2616 // function with an extra parameter, which is whether a call to
2617 // recover can succeed.  We then move the body of this function to
2618 // that one.  We then turn this function into a thunk which calls the
2619 // new one, passing the value of
2620 // __go_can_recover(__builtin_return_address()).  The function will be
2621 // marked as not splitting the stack.  This will cooperate with the
2622 // implementation of defer to make recover do the right thing.
2623
2624 void
2625 Gogo::build_recover_thunks()
2626 {
2627   Build_recover_thunks build_recover_thunks(this);
2628   this->traverse(&build_recover_thunks);
2629 }
2630
2631 // Look for named types to see whether we need to create an interface
2632 // method table.
2633
2634 class Build_method_tables : public Traverse
2635 {
2636  public:
2637   Build_method_tables(Gogo* gogo,
2638                       const std::vector<Interface_type*>& interfaces)
2639     : Traverse(traverse_types),
2640       gogo_(gogo), interfaces_(interfaces)
2641   { }
2642
2643   int
2644   type(Type*);
2645
2646  private:
2647   // The IR.
2648   Gogo* gogo_;
2649   // A list of locally defined interfaces which have hidden methods.
2650   const std::vector<Interface_type*>& interfaces_;
2651 };
2652
2653 // Build all required interface method tables for types.  We need to
2654 // ensure that we have an interface method table for every interface
2655 // which has a hidden method, for every named type which implements
2656 // that interface.  Normally we can just build interface method tables
2657 // as we need them.  However, in some cases we can require an
2658 // interface method table for an interface defined in a different
2659 // package for a type defined in that package.  If that interface and
2660 // type both use a hidden method, that is OK.  However, we will not be
2661 // able to build that interface method table when we need it, because
2662 // the type's hidden method will be static.  So we have to build it
2663 // here, and just refer it from other packages as needed.
2664
2665 void
2666 Gogo::build_interface_method_tables()
2667 {
2668   if (saw_errors())
2669     return;
2670
2671   std::vector<Interface_type*> hidden_interfaces;
2672   hidden_interfaces.reserve(this->interface_types_.size());
2673   for (std::vector<Interface_type*>::const_iterator pi =
2674          this->interface_types_.begin();
2675        pi != this->interface_types_.end();
2676        ++pi)
2677     {
2678       const Typed_identifier_list* methods = (*pi)->methods();
2679       if (methods == NULL)
2680         continue;
2681       for (Typed_identifier_list::const_iterator pm = methods->begin();
2682            pm != methods->end();
2683            ++pm)
2684         {
2685           if (Gogo::is_hidden_name(pm->name()))
2686             {
2687               hidden_interfaces.push_back(*pi);
2688               break;
2689             }
2690         }
2691     }
2692
2693   if (!hidden_interfaces.empty())
2694     {
2695       // Now traverse the tree looking for all named types.
2696       Build_method_tables bmt(this, hidden_interfaces);
2697       this->traverse(&bmt);
2698     }
2699
2700   // We no longer need the list of interfaces.
2701
2702   this->interface_types_.clear();
2703 }
2704
2705 // This is called for each type.  For a named type, for each of the
2706 // interfaces with hidden methods that it implements, create the
2707 // method table.
2708
2709 int
2710 Build_method_tables::type(Type* type)
2711 {
2712   Named_type* nt = type->named_type();
2713   if (nt != NULL)
2714     {
2715       for (std::vector<Interface_type*>::const_iterator p =
2716              this->interfaces_.begin();
2717            p != this->interfaces_.end();
2718            ++p)
2719         {
2720           // We ask whether a pointer to the named type implements the
2721           // interface, because a pointer can implement more methods
2722           // than a value.
2723           if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2724             {
2725               nt->interface_method_table(this->gogo_, *p, false);
2726               nt->interface_method_table(this->gogo_, *p, true);
2727             }
2728         }
2729     }
2730   return TRAVERSE_CONTINUE;
2731 }
2732
2733 // Traversal class used to check for return statements.
2734
2735 class Check_return_statements_traverse : public Traverse
2736 {
2737  public:
2738   Check_return_statements_traverse()
2739     : Traverse(traverse_functions)
2740   { }
2741
2742   int
2743   function(Named_object*);
2744 };
2745
2746 // Check that a function has a return statement if it needs one.
2747
2748 int
2749 Check_return_statements_traverse::function(Named_object* no)
2750 {
2751   Function* func = no->func_value();
2752   const Function_type* fntype = func->type();
2753   const Typed_identifier_list* results = fntype->results();
2754
2755   // We only need a return statement if there is a return value.
2756   if (results == NULL || results->empty())
2757     return TRAVERSE_CONTINUE;
2758
2759   if (func->block()->may_fall_through())
2760     error_at(func->location(), "control reaches end of non-void function");
2761
2762   return TRAVERSE_CONTINUE;
2763 }
2764
2765 // Check return statements.
2766
2767 void
2768 Gogo::check_return_statements()
2769 {
2770   Check_return_statements_traverse traverse;
2771   this->traverse(&traverse);
2772 }
2773
2774 // Get the unique prefix to use before all exported symbols.  This
2775 // must be unique across the entire link.
2776
2777 const std::string&
2778 Gogo::unique_prefix() const
2779 {
2780   go_assert(!this->unique_prefix_.empty());
2781   return this->unique_prefix_;
2782 }
2783
2784 // Set the unique prefix to use before all exported symbols.  This
2785 // comes from the command line option -fgo-prefix=XXX.
2786
2787 void
2788 Gogo::set_unique_prefix(const std::string& arg)
2789 {
2790   go_assert(this->unique_prefix_.empty());
2791   this->unique_prefix_ = arg;
2792   this->unique_prefix_specified_ = true;
2793 }
2794
2795 // Work out the package priority.  It is one more than the maximum
2796 // priority of an imported package.
2797
2798 int
2799 Gogo::package_priority() const
2800 {
2801   int priority = 0;
2802   for (Packages::const_iterator p = this->packages_.begin();
2803        p != this->packages_.end();
2804        ++p)
2805     if (p->second->priority() > priority)
2806       priority = p->second->priority();
2807   return priority + 1;
2808 }
2809
2810 // Export identifiers as requested.
2811
2812 void
2813 Gogo::do_exports()
2814 {
2815   // For now we always stream to a section.  Later we may want to
2816   // support streaming to a separate file.
2817   Stream_to_section stream;
2818
2819   Export exp(&stream);
2820   exp.register_builtin_types(this);
2821   exp.export_globals(this->package_name(),
2822                      this->unique_prefix(),
2823                      this->package_priority(),
2824                      (this->need_init_fn_ && !this->is_main_package()
2825                       ? this->get_init_fn_name()
2826                       : ""),
2827                      this->imported_init_fns_,
2828                      this->package_->bindings());
2829 }
2830
2831 // Find the blocks in order to convert named types defined in blocks.
2832
2833 class Convert_named_types : public Traverse
2834 {
2835  public:
2836   Convert_named_types(Gogo* gogo)
2837     : Traverse(traverse_blocks),
2838       gogo_(gogo)
2839   { }
2840
2841  protected:
2842   int
2843   block(Block* block);
2844
2845  private:
2846   Gogo* gogo_;
2847 };
2848
2849 int
2850 Convert_named_types::block(Block* block)
2851 {
2852   this->gogo_->convert_named_types_in_bindings(block->bindings());
2853   return TRAVERSE_CONTINUE;
2854 }
2855
2856 // Convert all named types to the backend representation.  Since named
2857 // types can refer to other types, this needs to be done in the right
2858 // sequence, which is handled by Named_type::convert.  Here we arrange
2859 // to call that for each named type.
2860
2861 void
2862 Gogo::convert_named_types()
2863 {
2864   this->convert_named_types_in_bindings(this->globals_);
2865   for (Packages::iterator p = this->packages_.begin();
2866        p != this->packages_.end();
2867        ++p)
2868     {
2869       Package* package = p->second;
2870       this->convert_named_types_in_bindings(package->bindings());
2871     }
2872
2873   Convert_named_types cnt(this);
2874   this->traverse(&cnt);
2875
2876   // Make all the builtin named types used for type descriptors, and
2877   // then convert them.  They will only be written out if they are
2878   // needed.
2879   Type::make_type_descriptor_type();
2880   Type::make_type_descriptor_ptr_type();
2881   Function_type::make_function_type_descriptor_type();
2882   Pointer_type::make_pointer_type_descriptor_type();
2883   Struct_type::make_struct_type_descriptor_type();
2884   Array_type::make_array_type_descriptor_type();
2885   Array_type::make_slice_type_descriptor_type();
2886   Map_type::make_map_type_descriptor_type();
2887   Map_type::make_map_descriptor_type();
2888   Channel_type::make_chan_type_descriptor_type();
2889   Interface_type::make_interface_type_descriptor_type();
2890   Type::convert_builtin_named_types(this);
2891
2892   Runtime::convert_types(this);
2893
2894   Function_type::convert_types(this);
2895
2896   this->named_types_are_converted_ = true;
2897 }
2898
2899 // Convert all names types in a set of bindings.
2900
2901 void
2902 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2903 {
2904   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2905        p != bindings->end_definitions();
2906        ++p)
2907     {
2908       if ((*p)->is_type())
2909         (*p)->type_value()->convert(this);
2910     }
2911 }
2912
2913 // Class Function.
2914
2915 Function::Function(Function_type* type, Function* enclosing, Block* block,
2916                    Location location)
2917   : type_(type), enclosing_(enclosing), results_(NULL),
2918     closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2919     defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2920     is_recover_thunk_(false), has_recover_thunk_(false)
2921 {
2922 }
2923
2924 // Create the named result variables.
2925
2926 void
2927 Function::create_result_variables(Gogo* gogo)
2928 {
2929   const Typed_identifier_list* results = this->type_->results();
2930   if (results == NULL || results->empty())
2931     return;
2932
2933   if (!results->front().name().empty())
2934     this->results_are_named_ = true;
2935
2936   this->results_ = new Results();
2937   this->results_->reserve(results->size());
2938
2939   Block* block = this->block_;
2940   int index = 0;
2941   for (Typed_identifier_list::const_iterator p = results->begin();
2942        p != results->end();
2943        ++p, ++index)
2944     {
2945       std::string name = p->name();
2946       if (name.empty() || Gogo::is_sink_name(name))
2947         {
2948           static int result_counter;
2949           char buf[100];
2950           snprintf(buf, sizeof buf, "$ret%d", result_counter);
2951           ++result_counter;
2952           name = gogo->pack_hidden_name(buf, false);
2953         }
2954       Result_variable* result = new Result_variable(p->type(), this, index,
2955                                                     p->location());
2956       Named_object* no = block->bindings()->add_result_variable(name, result);
2957       if (no->is_result_variable())
2958         this->results_->push_back(no);
2959       else
2960         {
2961           static int dummy_result_count;
2962           char buf[100];
2963           snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2964           ++dummy_result_count;
2965           name = gogo->pack_hidden_name(buf, false);
2966           no = block->bindings()->add_result_variable(name, result);
2967           go_assert(no->is_result_variable());
2968           this->results_->push_back(no);
2969         }
2970     }
2971 }
2972
2973 // Update the named result variables when cloning a function which
2974 // calls recover.
2975
2976 void
2977 Function::update_result_variables()
2978 {
2979   if (this->results_ == NULL)
2980     return;
2981
2982   for (Results::iterator p = this->results_->begin();
2983        p != this->results_->end();
2984        ++p)
2985     (*p)->result_var_value()->set_function(this);
2986 }
2987
2988 // Return the closure variable, creating it if necessary.
2989
2990 Named_object*
2991 Function::closure_var()
2992 {
2993   if (this->closure_var_ == NULL)
2994     {
2995       // We don't know the type of the variable yet.  We add fields as
2996       // we find them.
2997       Location loc = this->type_->location();
2998       Struct_field_list* sfl = new Struct_field_list;
2999       Type* struct_type = Type::make_struct_type(sfl, loc);
3000       Variable* var = new Variable(Type::make_pointer_type(struct_type),
3001                                    NULL, false, true, false, loc);
3002       var->set_is_used();
3003       this->closure_var_ = Named_object::make_variable("closure", NULL, var);
3004       // Note that the new variable is not in any binding contour.
3005     }
3006   return this->closure_var_;
3007 }
3008
3009 // Set the type of the closure variable.
3010
3011 void
3012 Function::set_closure_type()
3013 {
3014   if (this->closure_var_ == NULL)
3015     return;
3016   Named_object* closure = this->closure_var_;
3017   Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3018   unsigned int index = 0;
3019   for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3020        p != this->closure_fields_.end();
3021        ++p, ++index)
3022     {
3023       Named_object* no = p->first;
3024       char buf[20];
3025       snprintf(buf, sizeof buf, "%u", index);
3026       std::string n = no->name() + buf;
3027       Type* var_type;
3028       if (no->is_variable())
3029         var_type = no->var_value()->type();
3030       else
3031         var_type = no->result_var_value()->type();
3032       Type* field_type = Type::make_pointer_type(var_type);
3033       st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3034     }
3035 }
3036
3037 // Return whether this function is a method.
3038
3039 bool
3040 Function::is_method() const
3041 {
3042   return this->type_->is_method();
3043 }
3044
3045 // Add a label definition.
3046
3047 Label*
3048 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3049                                Location location)
3050 {
3051   Label* lnull = NULL;
3052   std::pair<Labels::iterator, bool> ins =
3053     this->labels_.insert(std::make_pair(label_name, lnull));
3054   Label* label;
3055   if (ins.second)
3056     {
3057       // This is a new label.
3058       label = new Label(label_name);
3059       ins.first->second = label;
3060     }
3061   else
3062     {
3063       // The label was already in the hash table.
3064       label = ins.first->second;
3065       if (label->is_defined())
3066         {
3067           error_at(location, "label %qs already defined",
3068                    Gogo::message_name(label_name).c_str());
3069           inform(label->location(), "previous definition of %qs was here",
3070                  Gogo::message_name(label_name).c_str());
3071           return new Label(label_name);
3072         }
3073     }
3074
3075   label->define(location, gogo->bindings_snapshot(location));
3076
3077   // Issue any errors appropriate for any previous goto's to this
3078   // label.
3079   const std::vector<Bindings_snapshot*>& refs(label->refs());
3080   for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3081        p != refs.end();
3082        ++p)
3083     (*p)->check_goto_to(gogo->current_block());
3084   label->clear_refs();
3085
3086   return label;
3087 }
3088
3089 // Add a reference to a label.
3090
3091 Label*
3092 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3093                               Location location, bool issue_goto_errors)
3094 {
3095   Label* lnull = NULL;
3096   std::pair<Labels::iterator, bool> ins =
3097     this->labels_.insert(std::make_pair(label_name, lnull));
3098   Label* label;
3099   if (!ins.second)
3100     {
3101       // The label was already in the hash table.
3102       label = ins.first->second;
3103     }
3104   else
3105     {
3106       go_assert(ins.first->second == NULL);
3107       label = new Label(label_name);
3108       ins.first->second = label;
3109     }
3110
3111   label->set_is_used();
3112
3113   if (issue_goto_errors)
3114     {
3115       Bindings_snapshot* snapshot = label->snapshot();
3116       if (snapshot != NULL)
3117         snapshot->check_goto_from(gogo->current_block(), location);
3118       else
3119         label->add_snapshot_ref(gogo->bindings_snapshot(location));
3120     }
3121
3122   return label;
3123 }
3124
3125 // Warn about labels that are defined but not used.
3126
3127 void
3128 Function::check_labels() const
3129 {
3130   for (Labels::const_iterator p = this->labels_.begin();
3131        p != this->labels_.end();
3132        p++)
3133     {
3134       Label* label = p->second;
3135       if (!label->is_used())
3136         error_at(label->location(), "label %qs defined and not used",
3137                  Gogo::message_name(label->name()).c_str());
3138     }
3139 }
3140
3141 // Swap one function with another.  This is used when building the
3142 // thunk we use to call a function which calls recover.  It may not
3143 // work for any other case.
3144
3145 void
3146 Function::swap_for_recover(Function *x)
3147 {
3148   go_assert(this->enclosing_ == x->enclosing_);
3149   std::swap(this->results_, x->results_);
3150   std::swap(this->closure_var_, x->closure_var_);
3151   std::swap(this->block_, x->block_);
3152   go_assert(this->location_ == x->location_);
3153   go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3154   go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3155 }
3156
3157 // Traverse the tree.
3158
3159 int
3160 Function::traverse(Traverse* traverse)
3161 {
3162   unsigned int traverse_mask = traverse->traverse_mask();
3163
3164   if ((traverse_mask
3165        & (Traverse::traverse_types | Traverse::traverse_expressions))
3166       != 0)
3167     {
3168       if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3169         return TRAVERSE_EXIT;
3170     }
3171
3172   // FIXME: We should check traverse_functions here if nested
3173   // functions are stored in block bindings.
3174   if (this->block_ != NULL
3175       && (traverse_mask
3176           & (Traverse::traverse_variables
3177              | Traverse::traverse_constants
3178              | Traverse::traverse_blocks
3179              | Traverse::traverse_statements
3180              | Traverse::traverse_expressions
3181              | Traverse::traverse_types)) != 0)
3182     {
3183       if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3184         return TRAVERSE_EXIT;
3185     }
3186
3187   return TRAVERSE_CONTINUE;
3188 }
3189
3190 // Work out types for unspecified variables and constants.
3191
3192 void
3193 Function::determine_types()
3194 {
3195   if (this->block_ != NULL)
3196     this->block_->determine_types();
3197 }
3198
3199 // Get a pointer to the variable representing the defer stack for this
3200 // function, making it if necessary.  The value of the variable is set
3201 // by the runtime routines to true if the function is returning,
3202 // rather than panicing through.  A pointer to this variable is used
3203 // as a marker for the functions on the defer stack associated with
3204 // this function.  A function-specific variable permits inlining a
3205 // function which uses defer.
3206
3207 Expression*
3208 Function::defer_stack(Location location)
3209 {
3210   if (this->defer_stack_ == NULL)
3211     {
3212       Type* t = Type::lookup_bool_type();
3213       Expression* n = Expression::make_boolean(false, location);
3214       this->defer_stack_ = Statement::make_temporary(t, n, location);
3215       this->defer_stack_->set_is_address_taken();
3216     }
3217   Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3218                                                          location);
3219   return Expression::make_unary(OPERATOR_AND, ref, location);
3220 }
3221
3222 // Export the function.
3223
3224 void
3225 Function::export_func(Export* exp, const std::string& name) const
3226 {
3227   Function::export_func_with_type(exp, name, this->type_);
3228 }
3229
3230 // Export a function with a type.
3231
3232 void
3233 Function::export_func_with_type(Export* exp, const std::string& name,
3234                                 const Function_type* fntype)
3235 {
3236   exp->write_c_string("func ");
3237
3238   if (fntype->is_method())
3239     {
3240       exp->write_c_string("(");
3241       exp->write_type(fntype->receiver()->type());
3242       exp->write_c_string(") ");
3243     }
3244
3245   exp->write_string(name);
3246
3247   exp->write_c_string(" (");
3248   const Typed_identifier_list* parameters = fntype->parameters();
3249   if (parameters != NULL)
3250     {
3251       bool is_varargs = fntype->is_varargs();
3252       bool first = true;
3253       for (Typed_identifier_list::const_iterator p = parameters->begin();
3254            p != parameters->end();
3255            ++p)
3256         {
3257           if (first)
3258             first = false;
3259           else
3260             exp->write_c_string(", ");
3261           if (!is_varargs || p + 1 != parameters->end())
3262             exp->write_type(p->type());
3263           else
3264             {
3265               exp->write_c_string("...");
3266               exp->write_type(p->type()->array_type()->element_type());
3267             }
3268         }
3269     }
3270   exp->write_c_string(")");
3271
3272   const Typed_identifier_list* results = fntype->results();
3273   if (results != NULL)
3274     {
3275       if (results->size() == 1)
3276         {
3277           exp->write_c_string(" ");
3278           exp->write_type(results->begin()->type());
3279         }
3280       else
3281         {
3282           exp->write_c_string(" (");
3283           bool first = true;
3284           for (Typed_identifier_list::const_iterator p = results->begin();
3285                p != results->end();
3286                ++p)
3287             {
3288               if (first)
3289                 first = false;
3290               else
3291                 exp->write_c_string(", ");
3292               exp->write_type(p->type());
3293             }
3294           exp->write_c_string(")");
3295         }
3296     }
3297   exp->write_c_string(";\n");
3298 }
3299
3300 // Import a function.
3301
3302 void
3303 Function::import_func(Import* imp, std::string* pname,
3304                       Typed_identifier** preceiver,
3305                       Typed_identifier_list** pparameters,
3306                       Typed_identifier_list** presults,
3307                       bool* is_varargs)
3308 {
3309   imp->require_c_string("func ");
3310
3311   *preceiver = NULL;
3312   if (imp->peek_char() == '(')
3313     {
3314       imp->require_c_string("(");
3315       Type* rtype = imp->read_type();
3316       *preceiver = new Typed_identifier(Import::import_marker, rtype,
3317                                         imp->location());
3318       imp->require_c_string(") ");
3319     }
3320
3321   *pname = imp->read_identifier();
3322
3323   Typed_identifier_list* parameters;
3324   *is_varargs = false;
3325   imp->require_c_string(" (");
3326   if (imp->peek_char() == ')')
3327     parameters = NULL;
3328   else
3329     {
3330       parameters = new Typed_identifier_list();
3331       while (true)
3332         {
3333           if (imp->match_c_string("..."))
3334             {
3335               imp->advance(3);
3336               *is_varargs = true;
3337             }
3338
3339           Type* ptype = imp->read_type();
3340           if (*is_varargs)
3341             ptype = Type::make_array_type(ptype, NULL);
3342           parameters->push_back(Typed_identifier(Import::import_marker,
3343                                                  ptype, imp->location()));
3344           if (imp->peek_char() != ',')
3345             break;
3346           go_assert(!*is_varargs);
3347           imp->require_c_string(", ");
3348         }
3349     }
3350   imp->require_c_string(")");
3351   *pparameters = parameters;
3352
3353   Typed_identifier_list* results;
3354   if (imp->peek_char() != ' ')
3355     results = NULL;
3356   else
3357     {
3358       results = new Typed_identifier_list();
3359       imp->require_c_string(" ");
3360       if (imp->peek_char() != '(')
3361         {
3362           Type* rtype = imp->read_type();
3363           results->push_back(Typed_identifier(Import::import_marker, rtype,
3364                                               imp->location()));
3365         }
3366       else
3367         {
3368           imp->require_c_string("(");
3369           while (true)
3370             {
3371               Type* rtype = imp->read_type();
3372               results->push_back(Typed_identifier(Import::import_marker,
3373                                                   rtype, imp->location()));
3374               if (imp->peek_char() != ',')
3375                 break;
3376               imp->require_c_string(", ");
3377             }
3378           imp->require_c_string(")");
3379         }
3380     }
3381   imp->require_c_string(";\n");
3382   *presults = results;
3383 }
3384
3385 // Class Block.
3386
3387 Block::Block(Block* enclosing, Location location)
3388   : enclosing_(enclosing), statements_(),
3389     bindings_(new Bindings(enclosing == NULL
3390                            ? NULL
3391                            : enclosing->bindings())),
3392     start_location_(location),
3393     end_location_(UNKNOWN_LOCATION)
3394 {
3395 }
3396
3397 // Add a statement to a block.
3398
3399 void
3400 Block::add_statement(Statement* statement)
3401 {
3402   this->statements_.push_back(statement);
3403 }
3404
3405 // Add a statement to the front of a block.  This is slow but is only
3406 // used for reference counts of parameters.
3407
3408 void
3409 Block::add_statement_at_front(Statement* statement)
3410 {
3411   this->statements_.insert(this->statements_.begin(), statement);
3412 }
3413
3414 // Replace a statement in a block.
3415
3416 void
3417 Block::replace_statement(size_t index, Statement* s)
3418 {
3419   go_assert(index < this->statements_.size());
3420   this->statements_[index] = s;
3421 }
3422
3423 // Add a statement before another statement.
3424
3425 void
3426 Block::insert_statement_before(size_t index, Statement* s)
3427 {
3428   go_assert(index < this->statements_.size());
3429   this->statements_.insert(this->statements_.begin() + index, s);
3430 }
3431
3432 // Add a statement after another statement.
3433
3434 void
3435 Block::insert_statement_after(size_t index, Statement* s)
3436 {
3437   go_assert(index < this->statements_.size());
3438   this->statements_.insert(this->statements_.begin() + index + 1, s);
3439 }
3440
3441 // Traverse the tree.
3442
3443 int
3444 Block::traverse(Traverse* traverse)
3445 {
3446   unsigned int traverse_mask = traverse->traverse_mask();
3447
3448   if ((traverse_mask & Traverse::traverse_blocks) != 0)
3449     {
3450       int t = traverse->block(this);
3451       if (t == TRAVERSE_EXIT)
3452         return TRAVERSE_EXIT;
3453       else if (t == TRAVERSE_SKIP_COMPONENTS)
3454         return TRAVERSE_CONTINUE;
3455     }
3456
3457   if ((traverse_mask
3458        & (Traverse::traverse_variables
3459           | Traverse::traverse_constants
3460           | Traverse::traverse_expressions
3461           | Traverse::traverse_types)) != 0)
3462     {
3463       const unsigned int e_or_t = (Traverse::traverse_expressions
3464                                    | Traverse::traverse_types);
3465       const unsigned int e_or_t_or_s = (e_or_t
3466                                         | Traverse::traverse_statements);
3467       for (Bindings::const_definitions_iterator pb =
3468              this->bindings_->begin_definitions();
3469            pb != this->bindings_->end_definitions();
3470            ++pb)
3471         {
3472           int t = TRAVERSE_CONTINUE;
3473           switch ((*pb)->classification())
3474             {
3475             case Named_object::NAMED_OBJECT_CONST:
3476               if ((traverse_mask & Traverse::traverse_constants) != 0)
3477                 t = traverse->constant(*pb, false);
3478               if (t == TRAVERSE_CONTINUE
3479                   && (traverse_mask & e_or_t) != 0)
3480                 {
3481                   Type* tc = (*pb)->const_value()->type();
3482                   if (tc != NULL
3483                       && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3484                     return TRAVERSE_EXIT;
3485                   t = (*pb)->const_value()->traverse_expression(traverse);
3486                 }
3487               break;
3488
3489             case Named_object::NAMED_OBJECT_VAR:
3490             case Named_object::NAMED_OBJECT_RESULT_VAR:
3491               if ((traverse_mask & Traverse::traverse_variables) != 0)
3492                 t = traverse->variable(*pb);
3493               if (t == TRAVERSE_CONTINUE
3494                   && (traverse_mask & e_or_t) != 0)
3495                 {
3496                   if ((*pb)->is_result_variable()
3497                       || (*pb)->var_value()->has_type())
3498                     {
3499                       Type* tv = ((*pb)->is_variable()
3500                                   ? (*pb)->var_value()->type()
3501                                   : (*pb)->result_var_value()->type());
3502                       if (tv != NULL
3503                           && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3504                         return TRAVERSE_EXIT;
3505                     }
3506                 }
3507               if (t == TRAVERSE_CONTINUE
3508                   && (traverse_mask & e_or_t_or_s) != 0
3509                   && (*pb)->is_variable())
3510                 t = (*pb)->var_value()->traverse_expression(traverse,
3511                                                             traverse_mask);
3512               break;
3513
3514             case Named_object::NAMED_OBJECT_FUNC:
3515             case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3516               go_unreachable();
3517
3518             case Named_object::NAMED_OBJECT_TYPE:
3519               if ((traverse_mask & e_or_t) != 0)
3520                 t = Type::traverse((*pb)->type_value(), traverse);
3521               break;
3522
3523             case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3524             case Named_object::NAMED_OBJECT_UNKNOWN:
3525               break;
3526
3527             case Named_object::NAMED_OBJECT_PACKAGE:
3528             case Named_object::NAMED_OBJECT_SINK: