OSDN Git Service

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