OSDN Git Service

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