26f6441d5b16078d9fcaca1697b46e6bb2f8dfed
[platform/upstream/gcc.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 <fstream>
10
11 #include "filenames.h"
12
13 #include "go-c.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
16 #include "go-dump.h"
17 #include "go-optimize.h"
18 #include "lex.h"
19 #include "types.h"
20 #include "statements.h"
21 #include "expressions.h"
22 #include "runtime.h"
23 #include "import.h"
24 #include "export.h"
25 #include "backend.h"
26 #include "gogo.h"
27
28 // Class Gogo.
29
30 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
31   : backend_(backend),
32     linemap_(linemap),
33     package_(NULL),
34     functions_(),
35     globals_(new Bindings(NULL)),
36     file_block_names_(),
37     imports_(),
38     imported_unsafe_(false),
39     current_file_imported_unsafe_(false),
40     packages_(),
41     init_functions_(),
42     var_deps_(),
43     need_init_fn_(false),
44     init_fn_name_(),
45     imported_init_fns_(),
46     pkgpath_(),
47     pkgpath_symbol_(),
48     prefix_(),
49     pkgpath_set_(false),
50     pkgpath_from_option_(false),
51     prefix_from_option_(false),
52     relative_import_path_(),
53     c_header_(),
54     check_divide_by_zero_(true),
55     check_divide_overflow_(true),
56     compiling_runtime_(false),
57     debug_escape_level_(0),
58     verify_types_(),
59     interface_types_(),
60     specific_type_functions_(),
61     specific_type_functions_are_written_(false),
62     named_types_are_converted_(false),
63     analysis_sets_(),
64     gc_roots_()
65 {
66   const Location loc = Linemap::predeclared_location();
67
68   Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
69                                                    RUNTIME_TYPE_KIND_UINT8);
70   this->add_named_type(uint8_type);
71   this->add_named_type(Type::make_integer_type("uint16", true,  16,
72                                                RUNTIME_TYPE_KIND_UINT16));
73   this->add_named_type(Type::make_integer_type("uint32", true,  32,
74                                                RUNTIME_TYPE_KIND_UINT32));
75   this->add_named_type(Type::make_integer_type("uint64", true,  64,
76                                                RUNTIME_TYPE_KIND_UINT64));
77
78   this->add_named_type(Type::make_integer_type("int8",  false,   8,
79                                                RUNTIME_TYPE_KIND_INT8));
80   this->add_named_type(Type::make_integer_type("int16", false,  16,
81                                                RUNTIME_TYPE_KIND_INT16));
82   Named_type* int32_type = Type::make_integer_type("int32", false,  32,
83                                                    RUNTIME_TYPE_KIND_INT32);
84   this->add_named_type(int32_type);
85   this->add_named_type(Type::make_integer_type("int64", false,  64,
86                                                RUNTIME_TYPE_KIND_INT64));
87
88   this->add_named_type(Type::make_float_type("float32", 32,
89                                              RUNTIME_TYPE_KIND_FLOAT32));
90   this->add_named_type(Type::make_float_type("float64", 64,
91                                              RUNTIME_TYPE_KIND_FLOAT64));
92
93   this->add_named_type(Type::make_complex_type("complex64", 64,
94                                                RUNTIME_TYPE_KIND_COMPLEX64));
95   this->add_named_type(Type::make_complex_type("complex128", 128,
96                                                RUNTIME_TYPE_KIND_COMPLEX128));
97
98   int int_type_size = pointer_size;
99   if (int_type_size < 32)
100     int_type_size = 32;
101   this->add_named_type(Type::make_integer_type("uint", true,
102                                                int_type_size,
103                                                RUNTIME_TYPE_KIND_UINT));
104   Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
105                                                  RUNTIME_TYPE_KIND_INT);
106   this->add_named_type(int_type);
107
108   this->add_named_type(Type::make_integer_type("uintptr", true,
109                                                pointer_size,
110                                                RUNTIME_TYPE_KIND_UINTPTR));
111
112   // "byte" is an alias for "uint8".
113   uint8_type->integer_type()->set_is_byte();
114   Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
115                                                     loc);
116   byte_type->type_value()->set_is_alias();
117   this->add_named_type(byte_type->type_value());
118
119   // "rune" is an alias for "int32".
120   int32_type->integer_type()->set_is_rune();
121   Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
122                                                     loc);
123   rune_type->type_value()->set_is_alias();
124   this->add_named_type(rune_type->type_value());
125
126   this->add_named_type(Type::make_named_bool_type());
127
128   this->add_named_type(Type::make_named_string_type());
129
130   // "error" is interface { Error() string }.
131   {
132     Typed_identifier_list *methods = new Typed_identifier_list;
133     Typed_identifier_list *results = new Typed_identifier_list;
134     results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
135     Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
136     methods->push_back(Typed_identifier("Error", method_type, loc));
137     Interface_type *error_iface = Type::make_interface_type(methods, loc);
138     error_iface->finalize_methods();
139     Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
140     this->add_named_type(error_type);
141   }
142
143   this->globals_->add_constant(Typed_identifier("true",
144                                                 Type::make_boolean_type(),
145                                                 loc),
146                                NULL,
147                                Expression::make_boolean(true, loc),
148                                0);
149   this->globals_->add_constant(Typed_identifier("false",
150                                                 Type::make_boolean_type(),
151                                                 loc),
152                                NULL,
153                                Expression::make_boolean(false, loc),
154                                0);
155
156   this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
157                                                 loc),
158                                NULL,
159                                Expression::make_nil(loc),
160                                0);
161
162   Type* abstract_int_type = Type::make_abstract_integer_type();
163   this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
164                                                 loc),
165                                NULL,
166                                Expression::make_iota(),
167                                0);
168
169   Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
170   new_type->set_is_varargs();
171   new_type->set_is_builtin();
172   this->globals_->add_function_declaration("new", NULL, new_type, loc);
173
174   Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
175   make_type->set_is_varargs();
176   make_type->set_is_builtin();
177   this->globals_->add_function_declaration("make", NULL, make_type, loc);
178
179   Typed_identifier_list* len_result = new Typed_identifier_list();
180   len_result->push_back(Typed_identifier("", int_type, loc));
181   Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
182                                                      loc);
183   len_type->set_is_builtin();
184   this->globals_->add_function_declaration("len", NULL, len_type, loc);
185
186   Typed_identifier_list* cap_result = new Typed_identifier_list();
187   cap_result->push_back(Typed_identifier("", int_type, loc));
188   Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
189                                                      loc);
190   cap_type->set_is_builtin();
191   this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
192
193   Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
194   print_type->set_is_varargs();
195   print_type->set_is_builtin();
196   this->globals_->add_function_declaration("print", NULL, print_type, loc);
197
198   print_type = Type::make_function_type(NULL, NULL, NULL, loc);
199   print_type->set_is_varargs();
200   print_type->set_is_builtin();
201   this->globals_->add_function_declaration("println", NULL, print_type, loc);
202
203   Type *empty = Type::make_empty_interface_type(loc);
204   Typed_identifier_list* panic_parms = new Typed_identifier_list();
205   panic_parms->push_back(Typed_identifier("e", empty, loc));
206   Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
207                                                        NULL, loc);
208   panic_type->set_is_builtin();
209   this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
210
211   Typed_identifier_list* recover_result = new Typed_identifier_list();
212   recover_result->push_back(Typed_identifier("", empty, loc));
213   Function_type* recover_type = Type::make_function_type(NULL, NULL,
214                                                          recover_result,
215                                                          loc);
216   recover_type->set_is_builtin();
217   this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
218
219   Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
220   close_type->set_is_varargs();
221   close_type->set_is_builtin();
222   this->globals_->add_function_declaration("close", NULL, close_type, loc);
223
224   Typed_identifier_list* copy_result = new Typed_identifier_list();
225   copy_result->push_back(Typed_identifier("", int_type, loc));
226   Function_type* copy_type = Type::make_function_type(NULL, NULL,
227                                                       copy_result, loc);
228   copy_type->set_is_varargs();
229   copy_type->set_is_builtin();
230   this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
231
232   Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
233   append_type->set_is_varargs();
234   append_type->set_is_builtin();
235   this->globals_->add_function_declaration("append", NULL, append_type, loc);
236
237   Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
238   complex_type->set_is_varargs();
239   complex_type->set_is_builtin();
240   this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
241
242   Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
243   real_type->set_is_varargs();
244   real_type->set_is_builtin();
245   this->globals_->add_function_declaration("real", NULL, real_type, loc);
246
247   Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
248   imag_type->set_is_varargs();
249   imag_type->set_is_builtin();
250   this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
251
252   Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
253   delete_type->set_is_varargs();
254   delete_type->set_is_builtin();
255   this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
256 }
257
258 // Convert a pkgpath into a string suitable for a symbol.  Note that
259 // this transformation is convenient but imperfect.  A -fgo-pkgpath
260 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
261 // possibly leading to link time errors.
262
263 std::string
264 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
265 {
266   std::string s = pkgpath;
267   for (size_t i = 0; i < s.length(); ++i)
268     {
269       char c = s[i];
270       if ((c >= 'a' && c <= 'z')
271           || (c >= 'A' && c <= 'Z')
272           || (c >= '0' && c <= '9'))
273         ;
274       else
275         s[i] = '_';
276     }
277   return s;
278 }
279
280 // Get the package path to use for type reflection data.  This should
281 // ideally be unique across the entire link.
282
283 const std::string&
284 Gogo::pkgpath() const
285 {
286   go_assert(this->pkgpath_set_);
287   return this->pkgpath_;
288 }
289
290 // Set the package path from the -fgo-pkgpath command line option.
291
292 void
293 Gogo::set_pkgpath(const std::string& arg)
294 {
295   go_assert(!this->pkgpath_set_);
296   this->pkgpath_ = arg;
297   this->pkgpath_set_ = true;
298   this->pkgpath_from_option_ = true;
299 }
300
301 // Get the package path to use for symbol names.
302
303 const std::string&
304 Gogo::pkgpath_symbol() const
305 {
306   go_assert(this->pkgpath_set_);
307   return this->pkgpath_symbol_;
308 }
309
310 // Set the unique prefix to use to determine the package path, from
311 // the -fgo-prefix command line option.
312
313 void
314 Gogo::set_prefix(const std::string& arg)
315 {
316   go_assert(!this->prefix_from_option_);
317   this->prefix_ = arg;
318   this->prefix_from_option_ = true;
319 }
320
321 // Munge name for use in an error message.
322
323 std::string
324 Gogo::message_name(const std::string& name)
325 {
326   return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
327 }
328
329 // Get the package name.
330
331 const std::string&
332 Gogo::package_name() const
333 {
334   go_assert(this->package_ != NULL);
335   return this->package_->package_name();
336 }
337
338 // Set the package name.
339
340 void
341 Gogo::set_package_name(const std::string& package_name,
342                        Location location)
343 {
344   if (this->package_ != NULL)
345     {
346       if (this->package_->package_name() != package_name)
347         go_error_at(location, "expected package %<%s%>",
348                     Gogo::message_name(this->package_->package_name()).c_str());
349       return;
350     }
351
352   // Now that we know the name of the package we are compiling, set
353   // the package path to use for reflect.Type.PkgPath and global
354   // symbol names.
355   if (this->pkgpath_set_)
356     this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
357   else
358     {
359       if (!this->prefix_from_option_ && package_name == "main")
360         {
361           this->pkgpath_ = package_name;
362           this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name);
363         }
364       else
365         {
366           if (!this->prefix_from_option_)
367             this->prefix_ = "go";
368           this->pkgpath_ = this->prefix_ + '.' + package_name;
369           this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.'
370                                    + Gogo::pkgpath_for_symbol(package_name));
371         }
372       this->pkgpath_set_ = true;
373     }
374
375   this->package_ = this->register_package(this->pkgpath_,
376                                           this->pkgpath_symbol_, location);
377   this->package_->set_package_name(package_name, location);
378
379   if (this->is_main_package())
380     {
381       // Declare "main" as a function which takes no parameters and
382       // returns no value.
383       Location uloc = Linemap::unknown_location();
384       this->declare_function(Gogo::pack_hidden_name("main", false),
385                              Type::make_function_type (NULL, NULL, NULL, uloc),
386                              uloc);
387     }
388 }
389
390 // Return whether this is the "main" package.  This is not true if
391 // -fgo-pkgpath or -fgo-prefix was used.
392
393 bool
394 Gogo::is_main_package() const
395 {
396   return (this->package_name() == "main"
397           && !this->pkgpath_from_option_
398           && !this->prefix_from_option_);
399 }
400
401 // Import a package.
402
403 void
404 Gogo::import_package(const std::string& filename,
405                      const std::string& local_name,
406                      bool is_local_name_exported,
407                      bool must_exist,
408                      Location location)
409 {
410   if (filename.empty())
411     {
412       go_error_at(location, "import path is empty");
413       return;
414     }
415
416   const char *pf = filename.data();
417   const char *pend = pf + filename.length();
418   while (pf < pend)
419     {
420       unsigned int c;
421       int adv = Lex::fetch_char(pf, &c);
422       if (adv == 0)
423         {
424           go_error_at(location, "import path contains invalid UTF-8 sequence");
425           return;
426         }
427       if (c == '\0')
428         {
429           go_error_at(location, "import path contains NUL");
430           return;
431         }
432       if (c < 0x20 || c == 0x7f)
433         {
434           go_error_at(location, "import path contains control character");
435           return;
436         }
437       if (c == '\\')
438         {
439           go_error_at(location, "import path contains backslash; use slash");
440           return;
441         }
442       if (Lex::is_unicode_space(c))
443         {
444           go_error_at(location, "import path contains space character");
445           return;
446         }
447       if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
448         {
449           go_error_at(location,
450                       "import path contains invalid character '%c'", c);
451           return;
452         }
453       pf += adv;
454     }
455
456   if (IS_ABSOLUTE_PATH(filename.c_str()))
457     {
458       go_error_at(location, "import path cannot be absolute path");
459       return;
460     }
461
462   if (local_name == "init")
463     go_error_at(location, "cannot import package as init");
464
465   if (filename == "unsafe")
466     {
467       this->import_unsafe(local_name, is_local_name_exported, location);
468       this->current_file_imported_unsafe_ = true;
469       return;
470     }
471
472   Imports::const_iterator p = this->imports_.find(filename);
473   if (p != this->imports_.end())
474     {
475       Package* package = p->second;
476       package->set_location(location);
477       std::string ln = local_name;
478       bool is_ln_exported = is_local_name_exported;
479       if (ln.empty())
480         {
481           ln = package->package_name();
482           go_assert(!ln.empty());
483           is_ln_exported = Lex::is_exported_name(ln);
484         }
485       if (ln == "_")
486         ;
487       else if (ln == ".")
488         {
489           Bindings* bindings = package->bindings();
490           for (Bindings::const_declarations_iterator p =
491                  bindings->begin_declarations();
492                p != bindings->end_declarations();
493                ++p)
494             this->add_dot_import_object(p->second);
495           std::string dot_alias = "." + package->package_name();
496           package->add_alias(dot_alias, location);
497         }
498       else
499         {
500           package->add_alias(ln, location);
501           ln = this->pack_hidden_name(ln, is_ln_exported);
502           this->package_->bindings()->add_package(ln, package);
503         }
504       return;
505     }
506
507   Import::Stream* stream = Import::open_package(filename, location,
508                                                 this->relative_import_path_);
509   if (stream == NULL)
510     {
511       if (must_exist)
512         go_error_at(location, "import file %qs not found", filename.c_str());
513       return;
514     }
515
516   Import imp(stream, location);
517   imp.register_builtin_types(this);
518   Package* package = imp.import(this, local_name, is_local_name_exported);
519   if (package != NULL)
520     {
521       if (package->pkgpath() == this->pkgpath())
522         go_error_at(location,
523                     ("imported package uses same package path as package "
524                      "being compiled (see -fgo-pkgpath option)"));
525
526       this->imports_.insert(std::make_pair(filename, package));
527     }
528
529   delete stream;
530 }
531
532 Import_init *
533 Gogo::lookup_init(const std::string& init_name)
534 {
535   Import_init tmp("", init_name, -1);
536   Import_init_set::iterator it = this->imported_init_fns_.find(&tmp);
537   return (it != this->imported_init_fns_.end()) ? *it : NULL;
538 }
539
540 // Add an import control function for an imported package to the list.
541
542 void
543 Gogo::add_import_init_fn(const std::string& package_name,
544                          const std::string& init_name, int prio)
545 {
546   for (Import_init_set::iterator p =
547          this->imported_init_fns_.begin();
548        p != this->imported_init_fns_.end();
549        ++p)
550     {
551       Import_init *ii = (*p);
552       if (ii->init_name() == init_name)
553         {
554           // If a test of package P1, built as part of package P1,
555           // imports package P2, and P2 imports P1 (perhaps
556           // indirectly), then we will see the same import name with
557           // different import priorities.  That is OK, so don't give
558           // an error about it.
559           if (ii->package_name() != package_name)
560             {
561               go_error_at(Linemap::unknown_location(),
562                        "duplicate package initialization name %qs",
563                        Gogo::message_name(init_name).c_str());
564               go_inform(Linemap::unknown_location(), "used by package %qs",
565                         Gogo::message_name(ii->package_name()).c_str());
566               go_inform(Linemap::unknown_location(), " and by package %qs",
567                         Gogo::message_name(package_name).c_str());
568             }
569           ii->set_priority(prio);
570           return;
571         }
572     }
573
574   Import_init* nii = new Import_init(package_name, init_name, prio);
575   this->imported_init_fns_.insert(nii);
576 }
577
578 // Return whether we are at the global binding level.
579
580 bool
581 Gogo::in_global_scope() const
582 {
583   return this->functions_.empty();
584 }
585
586 // Return the current binding contour.
587
588 Bindings*
589 Gogo::current_bindings()
590 {
591   if (!this->functions_.empty())
592     return this->functions_.back().blocks.back()->bindings();
593   else if (this->package_ != NULL)
594     return this->package_->bindings();
595   else
596     return this->globals_;
597 }
598
599 const Bindings*
600 Gogo::current_bindings() const
601 {
602   if (!this->functions_.empty())
603     return this->functions_.back().blocks.back()->bindings();
604   else if (this->package_ != NULL)
605     return this->package_->bindings();
606   else
607     return this->globals_;
608 }
609
610 void
611 Gogo::update_init_priority(Import_init* ii,
612                            std::set<const Import_init *>* visited)
613 {
614   visited->insert(ii);
615   int succ_prior = -1;
616
617   for (std::set<std::string>::const_iterator pci =
618            ii->precursors().begin();
619        pci != ii->precursors().end();
620        ++pci)
621     {
622       Import_init* succ = this->lookup_init(*pci);
623       if (visited->find(succ) == visited->end())
624         update_init_priority(succ, visited);
625       succ_prior = std::max(succ_prior, succ->priority());
626     }
627   if (ii->priority() <= succ_prior)
628     ii->set_priority(succ_prior + 1);
629 }
630
631 void
632 Gogo::recompute_init_priorities()
633 {
634   std::set<Import_init *> nonroots;
635
636   for (Import_init_set::const_iterator p =
637            this->imported_init_fns_.begin();
638        p != this->imported_init_fns_.end();
639        ++p)
640     {
641       const Import_init *ii = *p;
642       for (std::set<std::string>::const_iterator pci =
643                ii->precursors().begin();
644            pci != ii->precursors().end();
645            ++pci)
646         {
647           Import_init* ii = this->lookup_init(*pci);
648           nonroots.insert(ii);
649         }
650     }
651
652   // Recursively update priorities starting at roots.
653   std::set<const Import_init*> visited;
654   for (Import_init_set::iterator p =
655            this->imported_init_fns_.begin();
656        p != this->imported_init_fns_.end();
657        ++p)
658     {
659       Import_init* ii = *p;
660       if (nonroots.find(ii) != nonroots.end())
661         continue;
662       update_init_priority(ii, &visited);
663     }
664 }
665
666 // Add statements to INIT_STMTS which run the initialization
667 // functions for imported packages.  This is only used for the "main"
668 // package.
669
670 void
671 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction)
672 {
673   go_assert(this->is_main_package());
674
675   if (this->imported_init_fns_.empty())
676     return;
677
678   Location unknown_loc = Linemap::unknown_location();
679   Function_type* func_type =
680       Type::make_function_type(NULL, NULL, NULL, unknown_loc);
681   Btype* fntype = func_type->get_backend_fntype(this);
682
683   // Recompute init priorities based on a walk of the init graph.
684   recompute_init_priorities();
685
686   // We must call them in increasing priority order.
687   std::vector<const Import_init*> v;
688   for (Import_init_set::const_iterator p =
689          this->imported_init_fns_.begin();
690        p != this->imported_init_fns_.end();
691        ++p)
692     {
693       if ((*p)->priority() < 0)
694         go_error_at(Linemap::unknown_location(),
695                     "internal error: failed to set init priority for %s",
696                     (*p)->package_name().c_str());
697       v.push_back(*p);
698     }
699   std::sort(v.begin(), v.end(), priority_compare);
700
701   // We build calls to the init functions, which take no arguments.
702   std::vector<Bexpression*> empty_args;
703   for (std::vector<const Import_init*>::const_iterator p = v.begin();
704        p != v.end();
705        ++p)
706     {
707       const Import_init* ii = *p;
708       std::string user_name = ii->package_name() + ".init";
709       const std::string& init_name(ii->init_name());
710
711       Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
712                                                    true, true, true, false,
713                                                    false, unknown_loc);
714       Bexpression* pfunc_code =
715           this->backend()->function_code_expression(pfunc, unknown_loc);
716       Bexpression* pfunc_call =
717           this->backend()->call_expression(bfunction, pfunc_code, empty_args,
718                                            NULL, unknown_loc);
719       init_stmts.push_back(this->backend()->expression_statement(bfunction,
720                                                                  pfunc_call));
721     }
722 }
723
724 // Register global variables with the garbage collector.  We need to
725 // register all variables which can hold a pointer value.  They become
726 // roots during the mark phase.  We build a struct that is easy to
727 // hook into a list of roots.
728
729 // type gcRoot struct {
730 //      decl    unsafe.Pointer // Pointer to variable.
731 //      size    uintptr        // Total size of variable.
732 //      ptrdata uintptr        // Length of variable's gcdata.
733 //      gcdata  *byte          // Pointer mask.
734 // }
735 //
736 // type gcRootList struct {
737 //      next  *gcRootList
738 //      count int
739 //      roots [...]gcRoot
740 // }
741
742 // The last entry in the roots array has a NULL decl field.
743
744 void
745 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
746                        std::vector<Bstatement*>& init_stmts,
747                        Bfunction* init_bfn)
748 {
749   if (var_gc.empty() && this->gc_roots_.empty())
750     return;
751
752   Type* pvt = Type::make_pointer_type(Type::make_void_type());
753   Type* uintptr_type = Type::lookup_integer_type("uintptr");
754   Type* byte_type = this->lookup_global("byte")->type_value();
755   Type* pointer_byte_type = Type::make_pointer_type(byte_type);
756   Struct_type* root_type =
757     Type::make_builtin_struct_type(4,
758                                    "decl", pvt,
759                                    "size", uintptr_type,
760                                    "ptrdata", uintptr_type,
761                                    "gcdata", pointer_byte_type);
762
763   Location builtin_loc = Linemap::predeclared_location();
764   unsigned long roots_len = var_gc.size() + this->gc_roots_.size();
765   Expression* length = Expression::make_integer_ul(roots_len, NULL,
766                                                    builtin_loc);
767   Array_type* root_array_type = Type::make_array_type(root_type, length);
768   root_array_type->set_is_array_incomparable();
769
770   Type* int_type = Type::lookup_integer_type("int");
771   Struct_type* root_list_type =
772       Type::make_builtin_struct_type(3,
773                                      "next", pvt,
774                                      "count", int_type,
775                                      "roots", root_array_type);
776
777   // Build an initializer for the roots array.
778
779   Expression_list* roots_init = new Expression_list();
780
781   for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
782        p != var_gc.end();
783        ++p)
784     {
785       Expression_list* init = new Expression_list();
786
787       Location no_loc = (*p)->location();
788       Expression* decl = Expression::make_var_reference(*p, no_loc);
789       Expression* decl_addr =
790           Expression::make_unary(OPERATOR_AND, decl, no_loc);
791       decl_addr->unary_expression()->set_does_not_escape();
792       decl_addr = Expression::make_cast(pvt, decl_addr, no_loc);
793       init->push_back(decl_addr);
794
795       Expression* size =
796         Expression::make_type_info(decl->type(),
797                                    Expression::TYPE_INFO_SIZE);
798       init->push_back(size);
799
800       Expression* ptrdata =
801         Expression::make_type_info(decl->type(),
802                                    Expression::TYPE_INFO_BACKEND_PTRDATA);
803       init->push_back(ptrdata);
804
805       Expression* gcdata = Expression::make_ptrmask_symbol(decl->type());
806       init->push_back(gcdata);
807
808       Expression* root_ctor =
809           Expression::make_struct_composite_literal(root_type, init, no_loc);
810       roots_init->push_back(root_ctor);
811     }
812
813   for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin();
814        p != this->gc_roots_.end();
815        ++p)
816     {
817       Expression_list *init = new Expression_list();
818
819       Expression* expr = *p;
820       Location eloc = expr->location();
821       init->push_back(Expression::make_cast(pvt, expr, eloc));
822
823       Type* type = expr->type()->points_to();
824       go_assert(type != NULL);
825
826       Expression* size =
827         Expression::make_type_info(type,
828                                    Expression::TYPE_INFO_SIZE);
829       init->push_back(size);
830
831       Expression* ptrdata =
832         Expression::make_type_info(type,
833                                    Expression::TYPE_INFO_BACKEND_PTRDATA);
834       init->push_back(ptrdata);
835
836       Expression* gcdata = Expression::make_ptrmask_symbol(type);
837       init->push_back(gcdata);
838
839       Expression* root_ctor =
840         Expression::make_struct_composite_literal(root_type, init, eloc);
841       roots_init->push_back(root_ctor);
842     }
843
844   // Build a constructor for the struct.
845
846   Expression_list* root_list_init = new Expression_list();
847   root_list_init->push_back(Expression::make_nil(builtin_loc));
848   root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type,
849                                                         builtin_loc));
850
851   Expression* roots_ctor =
852       Expression::make_array_composite_literal(root_array_type, roots_init,
853                                                builtin_loc);
854   root_list_init->push_back(roots_ctor);
855
856   Expression* root_list_ctor =
857       Expression::make_struct_composite_literal(root_list_type, root_list_init,
858                                                 builtin_loc);
859
860   Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
861                                                  builtin_loc);
862   root_addr->unary_expression()->set_is_gc_root();
863   Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
864                                                   builtin_loc, 1, root_addr);
865
866   Translate_context context(this, NULL, NULL, NULL);
867   Bexpression* bcall = register_roots->get_backend(&context);
868   init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall));
869 }
870
871 // Get the name to use for the import control function.  If there is a
872 // global function or variable, then we know that that name must be
873 // unique in the link, and we use it as the basis for our name.
874
875 const std::string&
876 Gogo::get_init_fn_name()
877 {
878   if (this->init_fn_name_.empty())
879     {
880       go_assert(this->package_ != NULL);
881       if (this->is_main_package())
882         {
883           // Use a name which the runtime knows.
884           this->init_fn_name_ = "__go_init_main";
885         }
886       else
887         {
888           std::string s = this->pkgpath_symbol();
889           s.append("..import");
890           this->init_fn_name_ = s;
891         }
892     }
893
894   return this->init_fn_name_;
895 }
896
897 // Build the decl for the initialization function.
898
899 Named_object*
900 Gogo::initialization_function_decl()
901 {
902   std::string name = this->get_init_fn_name();
903   Location loc = this->package_->location();
904
905   Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
906   Function* initfn = new Function(fntype, NULL, NULL, loc);
907   return Named_object::make_function(name, NULL, initfn);
908 }
909
910 // Create the magic initialization function.  CODE_STMT is the
911 // code that it needs to run.
912
913 Named_object*
914 Gogo::create_initialization_function(Named_object* initfn,
915                                      Bstatement* code_stmt)
916 {
917   // Make sure that we thought we needed an initialization function,
918   // as otherwise we will not have reported it in the export data.
919   go_assert(this->is_main_package() || this->need_init_fn_);
920
921   if (initfn == NULL)
922     initfn = this->initialization_function_decl();
923
924   // Bind the initialization function code to a block.
925   Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
926   Location pkg_loc = this->package_->location();
927   std::vector<Bvariable*> vars;
928   this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
929
930   if (!this->backend()->function_set_body(fndecl, code_stmt))
931     {
932       go_assert(saw_errors());
933       return NULL;
934     }
935   return initfn;
936 }
937
938 // Search for references to VAR in any statements or called functions.
939
940 class Find_var : public Traverse
941 {
942  public:
943   // A hash table we use to avoid looping.  The index is the name of a
944   // named object.  We only look through objects defined in this
945   // package.
946   typedef Unordered_set(const void*) Seen_objects;
947
948   Find_var(Named_object* var, Seen_objects* seen_objects)
949     : Traverse(traverse_expressions),
950       var_(var), seen_objects_(seen_objects), found_(false)
951   { }
952
953   // Whether the variable was found.
954   bool
955   found() const
956   { return this->found_; }
957
958   int
959   expression(Expression**);
960
961  private:
962   // The variable we are looking for.
963   Named_object* var_;
964   // Names of objects we have already seen.
965   Seen_objects* seen_objects_;
966   // True if the variable was found.
967   bool found_;
968 };
969
970 // See if EXPR refers to VAR, looking through function calls and
971 // variable initializations.
972
973 int
974 Find_var::expression(Expression** pexpr)
975 {
976   Expression* e = *pexpr;
977
978   Var_expression* ve = e->var_expression();
979   if (ve != NULL)
980     {
981       Named_object* v = ve->named_object();
982       if (v == this->var_)
983         {
984           this->found_ = true;
985           return TRAVERSE_EXIT;
986         }
987
988       if (v->is_variable() && v->package() == NULL)
989         {
990           Expression* init = v->var_value()->init();
991           if (init != NULL)
992             {
993               std::pair<Seen_objects::iterator, bool> ins =
994                 this->seen_objects_->insert(v);
995               if (ins.second)
996                 {
997                   // This is the first time we have seen this name.
998                   if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
999                     return TRAVERSE_EXIT;
1000                 }
1001             }
1002         }
1003     }
1004
1005   // We traverse the code of any function or bound method we see.  Note that
1006   // this means that we will traverse the code of a function or bound method
1007   // whose address is taken even if it is not called.
1008   Func_expression* fe = e->func_expression();
1009   Bound_method_expression* bme = e->bound_method_expression();
1010   if (fe != NULL || bme != NULL)
1011     {
1012       const Named_object* f = fe != NULL ? fe->named_object() : bme->function();
1013       if (f->is_function() && f->package() == NULL)
1014         {
1015           std::pair<Seen_objects::iterator, bool> ins =
1016             this->seen_objects_->insert(f);
1017           if (ins.second)
1018             {
1019               // This is the first time we have seen this name.
1020               if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
1021                 return TRAVERSE_EXIT;
1022             }
1023         }
1024     }
1025
1026   Temporary_reference_expression* tre = e->temporary_reference_expression();
1027   if (tre != NULL)
1028     {
1029       Temporary_statement* ts = tre->statement();
1030       Expression* init = ts->init();
1031       if (init != NULL)
1032         {
1033           std::pair<Seen_objects::iterator, bool> ins =
1034             this->seen_objects_->insert(ts);
1035           if (ins.second)
1036             {
1037               // This is the first time we have seen this temporary
1038               // statement.
1039               if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1040                 return TRAVERSE_EXIT;
1041             }
1042         }
1043     }
1044
1045   return TRAVERSE_CONTINUE;
1046 }
1047
1048 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1049
1050 static bool
1051 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1052                     Named_object* var)
1053 {
1054   Find_var::Seen_objects seen_objects;
1055   Find_var find_var(var, &seen_objects);
1056   if (expr != NULL)
1057     Expression::traverse(&expr, &find_var);
1058   if (preinit != NULL)
1059     preinit->traverse(&find_var);
1060   if (dep != NULL)
1061     {
1062       Expression* init = dep->var_value()->init();
1063       if (init != NULL)
1064         Expression::traverse(&init, &find_var);
1065       if (dep->var_value()->has_pre_init())
1066         dep->var_value()->preinit()->traverse(&find_var);
1067     }
1068
1069   return find_var.found();
1070 }
1071
1072 // Sort variable initializations.  If the initialization expression
1073 // for variable A refers directly or indirectly to the initialization
1074 // expression for variable B, then we must initialize B before A.
1075
1076 class Var_init
1077 {
1078  public:
1079   Var_init()
1080     : var_(NULL), init_(NULL), dep_count_(0)
1081   { }
1082
1083   Var_init(Named_object* var, Bstatement* init)
1084     : var_(var), init_(init), dep_count_(0)
1085   { }
1086
1087   // Return the variable.
1088   Named_object*
1089   var() const
1090   { return this->var_; }
1091
1092   // Return the initialization expression.
1093   Bstatement*
1094   init() const
1095   { return this->init_; }
1096
1097   // Return the number of remaining dependencies.
1098   size_t
1099   dep_count() const
1100   { return this->dep_count_; }
1101
1102   // Increment the number of dependencies.
1103   void
1104   add_dependency()
1105   { ++this->dep_count_; }
1106
1107   // Decrement the number of dependencies.
1108   void
1109   remove_dependency()
1110   { --this->dep_count_; }
1111
1112  private:
1113   // The variable being initialized.
1114   Named_object* var_;
1115   // The initialization statement.
1116   Bstatement* init_;
1117   // The number of initializations this is dependent on.  A variable
1118   // initialization should not be emitted if any of its dependencies
1119   // have not yet been resolved.
1120   size_t dep_count_;
1121 };
1122
1123 // For comparing Var_init keys in a map.
1124
1125 inline bool
1126 operator<(const Var_init& v1, const Var_init& v2)
1127 { return v1.var()->name() < v2.var()->name(); }
1128
1129 typedef std::list<Var_init> Var_inits;
1130
1131 // Sort the variable initializations.  The rule we follow is that we
1132 // emit them in the order they appear in the array, except that if the
1133 // initialization expression for a variable V1 depends upon another
1134 // variable V2 then we initialize V1 after V2.
1135
1136 static void
1137 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1138 {
1139   if (var_inits->empty())
1140     return;
1141
1142   typedef std::pair<Named_object*, Named_object*> No_no;
1143   typedef std::map<No_no, bool> Cache;
1144   Cache cache;
1145
1146   // A mapping from a variable initialization to a set of
1147   // variable initializations that depend on it.
1148   typedef std::map<Var_init, std::set<Var_init*> > Init_deps;
1149   Init_deps init_deps;
1150   bool init_loop = false;
1151   for (Var_inits::iterator p1 = var_inits->begin();
1152        p1 != var_inits->end();
1153        ++p1)
1154     {
1155       Named_object* var = p1->var();
1156       Expression* init = var->var_value()->init();
1157       Block* preinit = var->var_value()->preinit();
1158       Named_object* dep = gogo->var_depends_on(var->var_value());
1159
1160       // Start walking through the list to see which variables VAR
1161       // needs to wait for.
1162       for (Var_inits::iterator p2 = var_inits->begin();
1163            p2 != var_inits->end();
1164            ++p2)
1165         {
1166           if (var == p2->var())
1167             continue;
1168
1169           Named_object* p2var = p2->var();
1170           No_no key(var, p2var);
1171           std::pair<Cache::iterator, bool> ins =
1172             cache.insert(std::make_pair(key, false));
1173           if (ins.second)
1174             ins.first->second = expression_requires(init, preinit, dep, p2var);
1175           if (ins.first->second)
1176             {
1177               // VAR depends on P2VAR.
1178               init_deps[*p2].insert(&(*p1));
1179               p1->add_dependency();
1180
1181               // Check for cycles.
1182               key = std::make_pair(p2var, var);
1183               ins = cache.insert(std::make_pair(key, false));
1184               if (ins.second)
1185                 ins.first->second =
1186                   expression_requires(p2var->var_value()->init(),
1187                                       p2var->var_value()->preinit(),
1188                                       gogo->var_depends_on(p2var->var_value()),
1189                                       var);
1190               if (ins.first->second)
1191                 {
1192                   go_error_at(var->location(),
1193                               ("initialization expressions for %qs and "
1194                                "%qs depend upon each other"),
1195                               var->message_name().c_str(),
1196                               p2var->message_name().c_str());
1197                   go_inform(p2->var()->location(), "%qs defined here",
1198                             p2var->message_name().c_str());
1199                   init_loop = true;
1200                   break;
1201                 }
1202             }
1203         }
1204     }
1205
1206   // If there are no dependencies then the declaration order is sorted.
1207   if (!init_deps.empty() && !init_loop)
1208     {
1209       // Otherwise, sort variable initializations by emitting all variables with
1210       // no dependencies in declaration order. VAR_INITS is already in
1211       // declaration order.
1212       Var_inits ready;
1213       while (!var_inits->empty())
1214         {
1215           Var_inits::iterator v1;;
1216           for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1)
1217             {
1218               if (v1->dep_count() == 0)
1219                 break;
1220             }
1221           go_assert(v1 != var_inits->end());
1222
1223           // V1 either has no dependencies or its dependencies have already
1224           // been emitted, add it to READY next.  When V1 is emitted, remove
1225           // a dependency from each V that depends on V1.
1226           ready.splice(ready.end(), *var_inits, v1);
1227
1228           Init_deps::iterator p1 = init_deps.find(*v1);
1229           if (p1 != init_deps.end())
1230             {
1231               std::set<Var_init*> resolved = p1->second;
1232               for (std::set<Var_init*>::iterator pv = resolved.begin();
1233                    pv != resolved.end();
1234                    ++pv)
1235                 (*pv)->remove_dependency();
1236               init_deps.erase(p1);
1237             }
1238         }
1239       var_inits->swap(ready);
1240       go_assert(init_deps.empty());
1241     }
1242
1243   // VAR_INITS is in the correct order.  For each VAR in VAR_INITS,
1244   // check for a loop of VAR on itself.
1245   // interpret as a loop.
1246   for (Var_inits::const_iterator p = var_inits->begin();
1247        p != var_inits->end();
1248        ++p)
1249     gogo->check_self_dep(p->var());
1250 }
1251
1252 // Give an error if the initialization expression for VAR depends on
1253 // itself.  We only check if INIT is not NULL and there is no
1254 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1255 // which we will interpret as a loop.
1256
1257 void
1258 Gogo::check_self_dep(Named_object* var)
1259 {
1260   Expression* init = var->var_value()->init();
1261   Block* preinit = var->var_value()->preinit();
1262   Named_object* dep = this->var_depends_on(var->var_value());
1263   if (init != NULL
1264       && dep == NULL
1265       && expression_requires(init, preinit, NULL, var))
1266     go_error_at(var->location(),
1267                 "initialization expression for %qs depends upon itself",
1268                 var->message_name().c_str());
1269 }
1270
1271 // Write out the global definitions.
1272
1273 void
1274 Gogo::write_globals()
1275 {
1276   this->build_interface_method_tables();
1277
1278   Bindings* bindings = this->current_bindings();
1279
1280   for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1281        p != bindings->end_declarations();
1282        ++p)
1283     {
1284       // If any function declarations needed a descriptor, make sure
1285       // we build it.
1286       Named_object* no = p->second;
1287       if (no->is_function_declaration())
1288         no->func_declaration_value()->build_backend_descriptor(this);
1289     }
1290
1291   // Lists of globally declared types, variables, constants, and functions
1292   // that must be defined.
1293   std::vector<Btype*> type_decls;
1294   std::vector<Bvariable*> var_decls;
1295   std::vector<Bexpression*> const_decls;
1296   std::vector<Bfunction*> func_decls;
1297
1298   // The init function declaration and associated Bfunction, if necessary.
1299   Named_object* init_fndecl = NULL;
1300   Bfunction* init_bfn = NULL;
1301
1302   std::vector<Bstatement*> init_stmts;
1303   std::vector<Bstatement*> var_init_stmts;
1304
1305   if (this->is_main_package())
1306     {
1307       init_fndecl = this->initialization_function_decl();
1308       init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl);
1309       this->init_imports(init_stmts, init_bfn);
1310     }
1311
1312   // A list of variable initializations.
1313   Var_inits var_inits;
1314
1315   // A list of variables which need to be registered with the garbage
1316   // collector.
1317   size_t count_definitions = bindings->size_definitions();
1318   std::vector<Named_object*> var_gc;
1319   var_gc.reserve(count_definitions);
1320
1321   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1322        p != bindings->end_definitions();
1323        ++p)
1324     {
1325       Named_object* no = *p;
1326       go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1327
1328       // There is nothing to do for a package.
1329       if (no->is_package())
1330         continue;
1331
1332       // There is nothing to do for an object which was imported from
1333       // a different package into the global scope.
1334       if (no->package() != NULL)
1335         continue;
1336
1337       // Skip blank named functions and constants.
1338       if ((no->is_function() && no->func_value()->is_sink())
1339           || (no->is_const() && no->const_value()->is_sink()))
1340         continue;
1341
1342       // There is nothing useful we can output for constants which
1343       // have ideal or non-integral type.
1344       if (no->is_const())
1345         {
1346           Type* type = no->const_value()->type();
1347           if (type == NULL)
1348             type = no->const_value()->expr()->type();
1349           if (type->is_abstract() || !type->is_numeric_type())
1350             continue;
1351         }
1352
1353       if (!no->is_variable())
1354         no->get_backend(this, const_decls, type_decls, func_decls);
1355       else
1356         {
1357           Variable* var = no->var_value();
1358           Bvariable* bvar = no->get_backend_variable(this, NULL);
1359           var_decls.push_back(bvar);
1360
1361           // Check for a sink variable, which may be used to run an
1362           // initializer purely for its side effects.
1363           bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1364
1365           Bstatement* var_init_stmt = NULL;
1366           if (!var->has_pre_init())
1367             {
1368               // If the backend representation of the variable initializer is
1369               // constant, we can just set the initial value using
1370               // global_var_set_init instead of during the init() function.
1371               // The initializer is constant if it is the zero-value of the
1372               // variable's type or if the initial value is an immutable value
1373               // that is not copied to the heap.
1374               bool is_static_initializer = false;
1375               if (var->init() == NULL)
1376                 is_static_initializer = true;
1377               else
1378                 {
1379                   Type* var_type = var->type();
1380                   Expression* init = var->init();
1381                   Expression* init_cast =
1382                       Expression::make_cast(var_type, init, var->location());
1383                   is_static_initializer = init_cast->is_static_initializer();
1384                 }
1385
1386               // Non-constant variable initializations might need to create
1387               // temporary variables, which will need the initialization
1388               // function as context.
1389               Named_object* var_init_fn;
1390               if (is_static_initializer)
1391                 var_init_fn = NULL;
1392               else
1393                 {
1394                   if (init_fndecl == NULL)
1395                     {
1396                       init_fndecl = this->initialization_function_decl();
1397                       Function* func = init_fndecl->func_value();
1398                       init_bfn = func->get_or_make_decl(this, init_fndecl);
1399                     }
1400                   var_init_fn = init_fndecl;
1401                 }
1402               Bexpression* var_binit = var->get_init(this, var_init_fn);
1403
1404               if (var_binit == NULL)
1405                 ;
1406               else if (is_static_initializer)
1407                 {
1408                   if (expression_requires(var->init(), NULL,
1409                                           this->var_depends_on(var), no))
1410                     go_error_at(no->location(),
1411                                 "initialization expression for %qs depends "
1412                                 "upon itself",
1413                                 no->message_name().c_str());
1414                   this->backend()->global_variable_set_init(bvar, var_binit);
1415                 }
1416               else if (is_sink)
1417                 var_init_stmt =
1418                     this->backend()->expression_statement(init_bfn, var_binit);
1419               else
1420                 {
1421                   Location loc = var->location();
1422                   Bexpression* var_expr =
1423                       this->backend()->var_expression(bvar, VE_lvalue, loc);
1424                   var_init_stmt =
1425                       this->backend()->assignment_statement(init_bfn, var_expr,
1426                                                             var_binit, loc);
1427                 }
1428             }
1429           else
1430             {
1431               // We are going to create temporary variables which
1432               // means that we need an fndecl.
1433               if (init_fndecl == NULL)
1434                 init_fndecl = this->initialization_function_decl();
1435
1436               Bvariable* var_decl = is_sink ? NULL : bvar;
1437               var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1438             }
1439
1440           if (var_init_stmt != NULL)
1441             {
1442               if (var->init() == NULL && !var->has_pre_init())
1443                 var_init_stmts.push_back(var_init_stmt);
1444               else
1445                 var_inits.push_back(Var_init(no, var_init_stmt));
1446             }
1447           else if (this->var_depends_on(var) != NULL)
1448             {
1449               // This variable is initialized from something that is
1450               // not in its init or preinit.  This variable needs to
1451               // participate in dependency analysis sorting, in case
1452               // some other variable depends on this one.
1453               Btype* btype = no->var_value()->type()->get_backend(this);
1454               Bexpression* zero = this->backend()->zero_expression(btype);
1455               Bstatement* zero_stmt =
1456                   this->backend()->expression_statement(init_bfn, zero);
1457               var_inits.push_back(Var_init(no, zero_stmt));
1458             }
1459
1460           // Collect a list of all global variables with pointers,
1461           // to register them for the garbage collector.
1462           if (!is_sink && var->type()->has_pointer())
1463             {
1464               // Avoid putting runtime.gcRoots itself on the list.
1465               if (this->compiling_runtime()
1466                   && this->package_name() == "runtime"
1467                   && Gogo::unpack_hidden_name(no->name()) == "gcRoots")
1468                 ;
1469               else
1470                 var_gc.push_back(no);
1471             }
1472         }
1473     }
1474
1475   // Register global variables with the garbage collector.
1476   this->register_gc_vars(var_gc, init_stmts, init_bfn);
1477
1478   // Simple variable initializations, after all variables are
1479   // registered.
1480   init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1481
1482   // Complete variable initializations, first sorting them into a
1483   // workable order.
1484   if (!var_inits.empty())
1485     {
1486       sort_var_inits(this, &var_inits);
1487       for (Var_inits::const_iterator p = var_inits.begin();
1488            p != var_inits.end();
1489            ++p)
1490         init_stmts.push_back(p->init());
1491     }
1492
1493   // After all the variables are initialized, call the init
1494   // functions if there are any.  Init functions take no arguments, so
1495   // we pass in EMPTY_ARGS to call them.
1496   std::vector<Bexpression*> empty_args;
1497   for (std::vector<Named_object*>::const_iterator p =
1498            this->init_functions_.begin();
1499        p != this->init_functions_.end();
1500        ++p)
1501     {
1502       Location func_loc = (*p)->location();
1503       Function* func = (*p)->func_value();
1504       Bfunction* initfn = func->get_or_make_decl(this, *p);
1505       Bexpression* func_code =
1506           this->backend()->function_code_expression(initfn, func_loc);
1507       Bexpression* call = this->backend()->call_expression(initfn, func_code,
1508                                                            empty_args,
1509                                                            NULL, func_loc);
1510       Bstatement* ist = this->backend()->expression_statement(initfn, call);
1511       init_stmts.push_back(ist);
1512     }
1513
1514   // Set up a magic function to do all the initialization actions.
1515   // This will be called if this package is imported.
1516   Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1517   if (this->need_init_fn_ || this->is_main_package())
1518     {
1519       init_fndecl =
1520         this->create_initialization_function(init_fndecl, init_fncode);
1521       if (init_fndecl != NULL)
1522         func_decls.push_back(init_fndecl->func_value()->get_decl());
1523     }
1524
1525   // We should not have seen any new bindings created during the conversion.
1526   go_assert(count_definitions == this->current_bindings()->size_definitions());
1527
1528   // Define all globally declared values.
1529   if (!saw_errors())
1530     this->backend()->write_global_definitions(type_decls, const_decls,
1531                                               func_decls, var_decls);
1532 }
1533
1534 // Return the current block.
1535
1536 Block*
1537 Gogo::current_block()
1538 {
1539   if (this->functions_.empty())
1540     return NULL;
1541   else
1542     return this->functions_.back().blocks.back();
1543 }
1544
1545 // Look up a name in the current binding contour.  If PFUNCTION is not
1546 // NULL, set it to the function in which the name is defined, or NULL
1547 // if the name is defined in global scope.
1548
1549 Named_object*
1550 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1551 {
1552   if (pfunction != NULL)
1553     *pfunction = NULL;
1554
1555   if (Gogo::is_sink_name(name))
1556     return Named_object::make_sink();
1557
1558   for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1559        p != this->functions_.rend();
1560        ++p)
1561     {
1562       Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1563       if (ret != NULL)
1564         {
1565           if (pfunction != NULL)
1566             *pfunction = p->function;
1567           return ret;
1568         }
1569     }
1570
1571   if (this->package_ != NULL)
1572     {
1573       Named_object* ret = this->package_->bindings()->lookup(name);
1574       if (ret != NULL)
1575         {
1576           if (ret->package() != NULL)
1577             {
1578               std::string dot_alias = "." + ret->package()->package_name();
1579               ret->package()->note_usage(dot_alias);
1580             }
1581           return ret;
1582         }
1583     }
1584
1585   // We do not look in the global namespace.  If we did, the global
1586   // namespace would effectively hide names which were defined in
1587   // package scope which we have not yet seen.  Instead,
1588   // define_global_names is called after parsing is over to connect
1589   // undefined names at package scope with names defined at global
1590   // scope.
1591
1592   return NULL;
1593 }
1594
1595 // Look up a name in the current block, without searching enclosing
1596 // blocks.
1597
1598 Named_object*
1599 Gogo::lookup_in_block(const std::string& name) const
1600 {
1601   go_assert(!this->functions_.empty());
1602   go_assert(!this->functions_.back().blocks.empty());
1603   return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1604 }
1605
1606 // Look up a name in the global namespace.
1607
1608 Named_object*
1609 Gogo::lookup_global(const char* name) const
1610 {
1611   return this->globals_->lookup(name);
1612 }
1613
1614 // Add an imported package.
1615
1616 Package*
1617 Gogo::add_imported_package(const std::string& real_name,
1618                            const std::string& alias_arg,
1619                            bool is_alias_exported,
1620                            const std::string& pkgpath,
1621                            const std::string& pkgpath_symbol,
1622                            Location location,
1623                            bool* padd_to_globals)
1624 {
1625   Package* ret = this->register_package(pkgpath, pkgpath_symbol, location);
1626   ret->set_package_name(real_name, location);
1627
1628   *padd_to_globals = false;
1629
1630   if (alias_arg == "_")
1631     ;
1632   else if (alias_arg == ".")
1633     {
1634       *padd_to_globals = true;
1635       std::string dot_alias = "." + real_name;
1636       ret->add_alias(dot_alias, location);
1637     }
1638   else
1639     {
1640       std::string alias = alias_arg;
1641       if (alias.empty())
1642         {
1643           alias = real_name;
1644           is_alias_exported = Lex::is_exported_name(alias);
1645         }
1646       ret->add_alias(alias, location);
1647       alias = this->pack_hidden_name(alias, is_alias_exported);
1648       Named_object* no = this->package_->bindings()->add_package(alias, ret);
1649       if (!no->is_package())
1650         return NULL;
1651     }
1652
1653   return ret;
1654 }
1655
1656 // Register a package.  This package may or may not be imported.  This
1657 // returns the Package structure for the package, creating if it
1658 // necessary.  LOCATION is the location of the import statement that
1659 // led us to see this package.  PKGPATH_SYMBOL is the symbol to use
1660 // for names in the package; it may be the empty string, in which case
1661 // we either get it later or make a guess when we need it.
1662
1663 Package*
1664 Gogo::register_package(const std::string& pkgpath,
1665                        const std::string& pkgpath_symbol, Location location)
1666 {
1667   Package* package = NULL;
1668   std::pair<Packages::iterator, bool> ins =
1669     this->packages_.insert(std::make_pair(pkgpath, package));
1670   if (!ins.second)
1671     {
1672       // We have seen this package name before.
1673       package = ins.first->second;
1674       go_assert(package != NULL && package->pkgpath() == pkgpath);
1675       if (!pkgpath_symbol.empty())
1676         package->set_pkgpath_symbol(pkgpath_symbol);
1677       if (Linemap::is_unknown_location(package->location()))
1678         package->set_location(location);
1679     }
1680   else
1681     {
1682       // First time we have seen this package name.
1683       package = new Package(pkgpath, pkgpath_symbol, location);
1684       go_assert(ins.first->second == NULL);
1685       ins.first->second = package;
1686     }
1687
1688   return package;
1689 }
1690
1691 // Start compiling a function.
1692
1693 Named_object*
1694 Gogo::start_function(const std::string& name, Function_type* type,
1695                      bool add_method_to_type, Location location)
1696 {
1697   bool at_top_level = this->functions_.empty();
1698
1699   Block* block = new Block(NULL, location);
1700
1701   Named_object* enclosing = (at_top_level
1702                          ? NULL
1703                          : this->functions_.back().function);
1704
1705   Function* function = new Function(type, enclosing, block, location);
1706
1707   if (type->is_method())
1708     {
1709       const Typed_identifier* receiver = type->receiver();
1710       Variable* this_param = new Variable(receiver->type(), NULL, false,
1711                                           true, true, location);
1712       std::string rname = receiver->name();
1713       if (rname.empty() || Gogo::is_sink_name(rname))
1714         {
1715           // We need to give receivers a name since they wind up in
1716           // DECL_ARGUMENTS.  FIXME.
1717           static unsigned int count;
1718           char buf[50];
1719           snprintf(buf, sizeof buf, "r.%u", count);
1720           ++count;
1721           rname = buf;
1722         }
1723       block->bindings()->add_variable(rname, NULL, this_param);
1724     }
1725
1726   const Typed_identifier_list* parameters = type->parameters();
1727   bool is_varargs = type->is_varargs();
1728   if (parameters != NULL)
1729     {
1730       for (Typed_identifier_list::const_iterator p = parameters->begin();
1731            p != parameters->end();
1732            ++p)
1733         {
1734           Variable* param = new Variable(p->type(), NULL, false, true, false,
1735                                          p->location());
1736           if (is_varargs && p + 1 == parameters->end())
1737             param->set_is_varargs_parameter();
1738
1739           std::string pname = p->name();
1740           if (pname.empty() || Gogo::is_sink_name(pname))
1741             {
1742               // We need to give parameters a name since they wind up
1743               // in DECL_ARGUMENTS.  FIXME.
1744               static unsigned int count;
1745               char buf[50];
1746               snprintf(buf, sizeof buf, "p.%u", count);
1747               ++count;
1748               pname = buf;
1749             }
1750           block->bindings()->add_variable(pname, NULL, param);
1751         }
1752     }
1753
1754   function->create_result_variables(this);
1755
1756   const std::string* pname;
1757   std::string nested_name;
1758   bool is_init = false;
1759   if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
1760     {
1761       if ((type->parameters() != NULL && !type->parameters()->empty())
1762           || (type->results() != NULL && !type->results()->empty()))
1763         go_error_at(location,
1764                     "func init must have no arguments and no return values");
1765       // There can be multiple "init" functions, so give them each a
1766       // different name.
1767       static int init_count;
1768       char buf[30];
1769       snprintf(buf, sizeof buf, ".$init%d", init_count);
1770       ++init_count;
1771       nested_name = buf;
1772       pname = &nested_name;
1773       is_init = true;
1774     }
1775   else if (!name.empty())
1776     pname = &name;
1777   else
1778     {
1779       // Invent a name for a nested function.
1780       static int nested_count;
1781       char buf[30];
1782       snprintf(buf, sizeof buf, ".$nested%d", nested_count);
1783       ++nested_count;
1784       nested_name = buf;
1785       pname = &nested_name;
1786     }
1787
1788   Named_object* ret;
1789   if (Gogo::is_sink_name(*pname))
1790     {
1791       static int sink_count;
1792       char buf[30];
1793       snprintf(buf, sizeof buf, ".$sink%d", sink_count);
1794       ++sink_count;
1795       ret = Named_object::make_function(buf, NULL, function);
1796       ret->func_value()->set_is_sink();
1797
1798       if (!type->is_method())
1799         ret = this->package_->bindings()->add_named_object(ret);
1800       else if (add_method_to_type)
1801         {
1802           // We should report errors even for sink methods.
1803           Type* rtype = type->receiver()->type();
1804           // Avoid points_to and deref to avoid getting an error if
1805           // the type is not yet defined.
1806           if (rtype->classification() == Type::TYPE_POINTER)
1807             rtype = rtype->points_to();
1808           while (rtype->named_type() != NULL
1809                  && rtype->named_type()->is_alias())
1810             rtype = rtype->named_type()->real_type()->forwarded();
1811           if (rtype->is_error_type())
1812             ;
1813           else if (rtype->named_type() != NULL)
1814             {
1815               if (rtype->named_type()->named_object()->package() != NULL)
1816                 go_error_at(type->receiver()->location(),
1817                             "may not define methods on non-local type");
1818             }
1819           else if (rtype->forward_declaration_type() != NULL)
1820             {
1821               // Go ahead and add the method in case we need to report
1822               // an error when we see the definition.
1823               rtype->forward_declaration_type()->add_existing_method(ret);
1824             }
1825           else
1826             go_error_at(type->receiver()->location(),
1827                         ("invalid receiver type "
1828                          "(receiver must be a named type)"));
1829         }
1830     }
1831   else if (!type->is_method())
1832     {
1833       ret = this->package_->bindings()->add_function(*pname, NULL, function);
1834       if (!ret->is_function() || ret->func_value() != function)
1835         {
1836           // Redefinition error.  Invent a name to avoid knockon
1837           // errors.
1838           static int redefinition_count;
1839           char buf[30];
1840           snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
1841           ++redefinition_count;
1842           ret = this->package_->bindings()->add_function(buf, NULL, function);
1843         }
1844     }
1845   else
1846     {
1847       if (!add_method_to_type)
1848         ret = Named_object::make_function(name, NULL, function);
1849       else
1850         {
1851           go_assert(at_top_level);
1852           Type* rtype = type->receiver()->type();
1853
1854           // We want to look through the pointer created by the
1855           // parser, without getting an error if the type is not yet
1856           // defined.
1857           if (rtype->classification() == Type::TYPE_POINTER)
1858             rtype = rtype->points_to();
1859
1860           while (rtype->named_type() != NULL
1861                  && rtype->named_type()->is_alias())
1862             rtype = rtype->named_type()->real_type()->forwarded();
1863
1864           if (rtype->is_error_type())
1865             ret = Named_object::make_function(name, NULL, function);
1866           else if (rtype->named_type() != NULL)
1867             {
1868               if (rtype->named_type()->named_object()->package() != NULL)
1869                 {
1870                   go_error_at(type->receiver()->location(),
1871                               "may not define methods on non-local type");
1872                   ret = Named_object::make_function(name, NULL, function);
1873                 }
1874               else
1875                 {
1876                   ret = rtype->named_type()->add_method(name, function);
1877                   if (!ret->is_function())
1878                     {
1879                       // Redefinition error.
1880                       ret = Named_object::make_function(name, NULL, function);
1881                     }
1882                 }
1883             }
1884           else if (rtype->forward_declaration_type() != NULL)
1885             {
1886               Named_object* type_no =
1887                 rtype->forward_declaration_type()->named_object();
1888               if (type_no->is_unknown())
1889                 {
1890                   // If we are seeing methods it really must be a
1891                   // type.  Declare it as such.  An alternative would
1892                   // be to support lists of methods for unknown
1893                   // expressions.  Either way the error messages if
1894                   // this is not a type are going to get confusing.
1895                   Named_object* declared =
1896                     this->declare_package_type(type_no->name(),
1897                                                type_no->location());
1898                   go_assert(declared
1899                              == type_no->unknown_value()->real_named_object());
1900                 }
1901               ret = rtype->forward_declaration_type()->add_method(name,
1902                                                                   function);
1903             }
1904           else
1905             {
1906               go_error_at(type->receiver()->location(),
1907                           ("invalid receiver type (receiver must "
1908                            "be a named type)"));
1909               ret = Named_object::make_function(name, NULL, function);
1910             }
1911         }
1912       this->package_->bindings()->add_method(ret);
1913     }
1914
1915   this->functions_.resize(this->functions_.size() + 1);
1916   Open_function& of(this->functions_.back());
1917   of.function = ret;
1918   of.blocks.push_back(block);
1919
1920   if (is_init)
1921     {
1922       this->init_functions_.push_back(ret);
1923       this->need_init_fn_ = true;
1924     }
1925
1926   return ret;
1927 }
1928
1929 // Finish compiling a function.
1930
1931 void
1932 Gogo::finish_function(Location location)
1933 {
1934   this->finish_block(location);
1935   go_assert(this->functions_.back().blocks.empty());
1936   this->functions_.pop_back();
1937 }
1938
1939 // Return the current function.
1940
1941 Named_object*
1942 Gogo::current_function() const
1943 {
1944   go_assert(!this->functions_.empty());
1945   return this->functions_.back().function;
1946 }
1947
1948 // Start a new block.
1949
1950 void
1951 Gogo::start_block(Location location)
1952 {
1953   go_assert(!this->functions_.empty());
1954   Block* block = new Block(this->current_block(), location);
1955   this->functions_.back().blocks.push_back(block);
1956 }
1957
1958 // Finish a block.
1959
1960 Block*
1961 Gogo::finish_block(Location location)
1962 {
1963   go_assert(!this->functions_.empty());
1964   go_assert(!this->functions_.back().blocks.empty());
1965   Block* block = this->functions_.back().blocks.back();
1966   this->functions_.back().blocks.pop_back();
1967   block->set_end_location(location);
1968   return block;
1969 }
1970
1971 // Add an erroneous name.
1972
1973 Named_object*
1974 Gogo::add_erroneous_name(const std::string& name)
1975 {
1976   return this->package_->bindings()->add_erroneous_name(name);
1977 }
1978
1979 // Add an unknown name.
1980
1981 Named_object*
1982 Gogo::add_unknown_name(const std::string& name, Location location)
1983 {
1984   return this->package_->bindings()->add_unknown_name(name, location);
1985 }
1986
1987 // Declare a function.
1988
1989 Named_object*
1990 Gogo::declare_function(const std::string& name, Function_type* type,
1991                        Location location)
1992 {
1993   if (!type->is_method())
1994     return this->current_bindings()->add_function_declaration(name, NULL, type,
1995                                                               location);
1996   else
1997     {
1998       // We don't bother to add this to the list of global
1999       // declarations.
2000       Type* rtype = type->receiver()->type();
2001
2002       // We want to look through the pointer created by the
2003       // parser, without getting an error if the type is not yet
2004       // defined.
2005       if (rtype->classification() == Type::TYPE_POINTER)
2006         rtype = rtype->points_to();
2007
2008       if (rtype->is_error_type())
2009         return NULL;
2010       else if (rtype->named_type() != NULL)
2011         return rtype->named_type()->add_method_declaration(name, NULL, type,
2012                                                            location);
2013       else if (rtype->forward_declaration_type() != NULL)
2014         {
2015           Forward_declaration_type* ftype = rtype->forward_declaration_type();
2016           return ftype->add_method_declaration(name, NULL, type, location);
2017         }
2018       else
2019         {
2020           go_error_at(type->receiver()->location(),
2021                       "invalid receiver type (receiver must be a named type)");
2022           return Named_object::make_erroneous_name(name);
2023         }
2024     }
2025 }
2026
2027 // Add a label definition.
2028
2029 Label*
2030 Gogo::add_label_definition(const std::string& label_name,
2031                            Location location)
2032 {
2033   go_assert(!this->functions_.empty());
2034   Function* func = this->functions_.back().function->func_value();
2035   Label* label = func->add_label_definition(this, label_name, location);
2036   this->add_statement(Statement::make_label_statement(label, location));
2037   return label;
2038 }
2039
2040 // Add a label reference.
2041
2042 Label*
2043 Gogo::add_label_reference(const std::string& label_name,
2044                           Location location, bool issue_goto_errors)
2045 {
2046   go_assert(!this->functions_.empty());
2047   Function* func = this->functions_.back().function->func_value();
2048   return func->add_label_reference(this, label_name, location,
2049                                    issue_goto_errors);
2050 }
2051
2052 // Return the current binding state.
2053
2054 Bindings_snapshot*
2055 Gogo::bindings_snapshot(Location location)
2056 {
2057   return new Bindings_snapshot(this->current_block(), location);
2058 }
2059
2060 // Add a statement.
2061
2062 void
2063 Gogo::add_statement(Statement* statement)
2064 {
2065   go_assert(!this->functions_.empty()
2066              && !this->functions_.back().blocks.empty());
2067   this->functions_.back().blocks.back()->add_statement(statement);
2068 }
2069
2070 // Add a block.
2071
2072 void
2073 Gogo::add_block(Block* block, Location location)
2074 {
2075   go_assert(!this->functions_.empty()
2076              && !this->functions_.back().blocks.empty());
2077   Statement* statement = Statement::make_block_statement(block, location);
2078   this->functions_.back().blocks.back()->add_statement(statement);
2079 }
2080
2081 // Add a constant.
2082
2083 Named_object*
2084 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
2085                    int iota_value)
2086 {
2087   return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
2088 }
2089
2090 // Add a type.
2091
2092 void
2093 Gogo::add_type(const std::string& name, Type* type, Location location)
2094 {
2095   Named_object* no = this->current_bindings()->add_type(name, NULL, type,
2096                                                         location);
2097   if (!this->in_global_scope() && no->is_type())
2098     {
2099       Named_object* f = this->functions_.back().function;
2100       unsigned int index;
2101       if (f->is_function())
2102         index = f->func_value()->new_local_type_index();
2103       else
2104         index = 0;
2105       no->type_value()->set_in_function(f, index);
2106     }
2107 }
2108
2109 // Add a named type.
2110
2111 void
2112 Gogo::add_named_type(Named_type* type)
2113 {
2114   go_assert(this->in_global_scope());
2115   this->current_bindings()->add_named_type(type);
2116 }
2117
2118 // Declare a type.
2119
2120 Named_object*
2121 Gogo::declare_type(const std::string& name, Location location)
2122 {
2123   Bindings* bindings = this->current_bindings();
2124   Named_object* no = bindings->add_type_declaration(name, NULL, location);
2125   if (!this->in_global_scope() && no->is_type_declaration())
2126     {
2127       Named_object* f = this->functions_.back().function;
2128       unsigned int index;
2129       if (f->is_function())
2130         index = f->func_value()->new_local_type_index();
2131       else
2132         index = 0;
2133       no->type_declaration_value()->set_in_function(f, index);
2134     }
2135   return no;
2136 }
2137
2138 // Declare a type at the package level.
2139
2140 Named_object*
2141 Gogo::declare_package_type(const std::string& name, Location location)
2142 {
2143   return this->package_->bindings()->add_type_declaration(name, NULL, location);
2144 }
2145
2146 // Declare a function at the package level.
2147
2148 Named_object*
2149 Gogo::declare_package_function(const std::string& name, Function_type* type,
2150                                Location location)
2151 {
2152   return this->package_->bindings()->add_function_declaration(name, NULL, type,
2153                                                               location);
2154 }
2155
2156 // Define a type which was already declared.
2157
2158 void
2159 Gogo::define_type(Named_object* no, Named_type* type)
2160 {
2161   this->current_bindings()->define_type(no, type);
2162 }
2163
2164 // Add a variable.
2165
2166 Named_object*
2167 Gogo::add_variable(const std::string& name, Variable* variable)
2168 {
2169   Named_object* no = this->current_bindings()->add_variable(name, NULL,
2170                                                             variable);
2171
2172   // In a function the middle-end wants to see a DECL_EXPR node.
2173   if (no != NULL
2174       && no->is_variable()
2175       && !no->var_value()->is_parameter()
2176       && !this->functions_.empty())
2177     this->add_statement(Statement::make_variable_declaration(no));
2178
2179   return no;
2180 }
2181
2182 // Add a sink--a reference to the blank identifier _.
2183
2184 Named_object*
2185 Gogo::add_sink()
2186 {
2187   return Named_object::make_sink();
2188 }
2189
2190 // Add a named object for a dot import.
2191
2192 void
2193 Gogo::add_dot_import_object(Named_object* no)
2194 {
2195   // If the name already exists, then it was defined in some file seen
2196   // earlier.  If the earlier name is just a declaration, don't add
2197   // this name, because that will cause the previous declaration to
2198   // merge to this imported name, which should not happen.  Just add
2199   // this name to the list of file block names to get appropriate
2200   // errors if we see a later definition.
2201   Named_object* e = this->package_->bindings()->lookup(no->name());
2202   if (e != NULL && e->package() == NULL)
2203     {
2204       if (e->is_unknown())
2205         e = e->resolve();
2206       if (e->package() == NULL
2207           && (e->is_type_declaration()
2208               || e->is_function_declaration()
2209               || e->is_unknown()))
2210         {
2211           this->add_file_block_name(no->name(), no->location());
2212           return;
2213         }
2214     }
2215
2216   this->current_bindings()->add_named_object(no);
2217 }
2218
2219 // Add a linkname.  This implements the go:linkname compiler directive.
2220 // We only support this for functions and function declarations.
2221
2222 void
2223 Gogo::add_linkname(const std::string& go_name, bool is_exported,
2224                    const std::string& ext_name, Location loc)
2225 {
2226   Named_object* no =
2227     this->package_->bindings()->lookup(this->pack_hidden_name(go_name,
2228                                                               is_exported));
2229   if (no == NULL)
2230     go_error_at(loc, "%s is not defined", go_name.c_str());
2231   else if (no->is_function())
2232     no->func_value()->set_asm_name(ext_name);
2233   else if (no->is_function_declaration())
2234     no->func_declaration_value()->set_asm_name(ext_name);
2235   else
2236     go_error_at(loc,
2237                 ("%s is not a function; "
2238                  "//go:linkname is only supported for functions"),
2239                 go_name.c_str());
2240 }
2241
2242 // Mark all local variables used.  This is used when some types of
2243 // parse error occur.
2244
2245 void
2246 Gogo::mark_locals_used()
2247 {
2248   for (Open_functions::iterator pf = this->functions_.begin();
2249        pf != this->functions_.end();
2250        ++pf)
2251     {
2252       for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2253            pb != pf->blocks.end();
2254            ++pb)
2255         (*pb)->bindings()->mark_locals_used();
2256     }
2257 }
2258
2259 // Record that we've seen an interface type.
2260
2261 void
2262 Gogo::record_interface_type(Interface_type* itype)
2263 {
2264   this->interface_types_.push_back(itype);
2265 }
2266
2267 // Return an erroneous name that indicates that an error has already
2268 // been reported.
2269
2270 std::string
2271 Gogo::erroneous_name()
2272 {
2273   static int erroneous_count;
2274   char name[50];
2275   snprintf(name, sizeof name, "$erroneous%d", erroneous_count);
2276   ++erroneous_count;
2277   return name;
2278 }
2279
2280 // Return whether a name is an erroneous name.
2281
2282 bool
2283 Gogo::is_erroneous_name(const std::string& name)
2284 {
2285   return name.compare(0, 10, "$erroneous") == 0;
2286 }
2287
2288 // Return a name for a thunk object.
2289
2290 std::string
2291 Gogo::thunk_name()
2292 {
2293   static int thunk_count;
2294   char thunk_name[50];
2295   snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
2296   ++thunk_count;
2297   return thunk_name;
2298 }
2299
2300 // Return whether a function is a thunk.
2301
2302 bool
2303 Gogo::is_thunk(const Named_object* no)
2304 {
2305   return no->name().compare(0, 6, "$thunk") == 0;
2306 }
2307
2308 // Define the global names.  We do this only after parsing all the
2309 // input files, because the program might define the global names
2310 // itself.
2311
2312 void
2313 Gogo::define_global_names()
2314 {
2315   if (this->is_main_package())
2316     {
2317       // Every Go program has to import the runtime package, so that
2318       // it is properly initialized.
2319       this->import_package("runtime", "_", false, false,
2320                            Linemap::predeclared_location());
2321     }
2322
2323   for (Bindings::const_declarations_iterator p =
2324          this->globals_->begin_declarations();
2325        p != this->globals_->end_declarations();
2326        ++p)
2327     {
2328       Named_object* global_no = p->second;
2329       std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2330       Named_object* no = this->package_->bindings()->lookup(name);
2331       if (no == NULL)
2332         continue;
2333       no = no->resolve();
2334       if (no->is_type_declaration())
2335         {
2336           if (global_no->is_type())
2337             {
2338               if (no->type_declaration_value()->has_methods())
2339                 {
2340                   for (std::vector<Named_object*>::const_iterator p =
2341                          no->type_declaration_value()->methods()->begin();
2342                        p != no->type_declaration_value()->methods()->end();
2343                        p++)
2344                     go_error_at((*p)->location(),
2345                                 "may not define methods on non-local type");
2346                 }
2347               no->set_type_value(global_no->type_value());
2348             }
2349           else
2350             {
2351               go_error_at(no->location(), "expected type");
2352               Type* errtype = Type::make_error_type();
2353               Named_object* err =
2354                 Named_object::make_type("erroneous_type", NULL, errtype,
2355                                         Linemap::predeclared_location());
2356               no->set_type_value(err->type_value());
2357             }
2358         }
2359       else if (no->is_unknown())
2360         no->unknown_value()->set_real_named_object(global_no);
2361     }
2362
2363   // Give an error if any name is defined in both the package block
2364   // and the file block.  For example, this can happen if one file
2365   // imports "fmt" and another file defines a global variable fmt.
2366   for (Bindings::const_declarations_iterator p =
2367          this->package_->bindings()->begin_declarations();
2368        p != this->package_->bindings()->end_declarations();
2369        ++p)
2370     {
2371       if (p->second->is_unknown()
2372           && p->second->unknown_value()->real_named_object() == NULL)
2373         {
2374           // No point in warning about an undefined name, as we will
2375           // get other errors later anyhow.
2376           continue;
2377         }
2378       File_block_names::const_iterator pf =
2379         this->file_block_names_.find(p->second->name());
2380       if (pf != this->file_block_names_.end())
2381         {
2382           std::string n = p->second->message_name();
2383           go_error_at(p->second->location(),
2384                       "%qs defined as both imported name and global name",
2385                       n.c_str());
2386           go_inform(pf->second, "%qs imported here", n.c_str());
2387         }
2388
2389       // No package scope identifier may be named "init".
2390       if (!p->second->is_function()
2391           && Gogo::unpack_hidden_name(p->second->name()) == "init")
2392         {
2393           go_error_at(p->second->location(),
2394                       "cannot declare init - must be func");
2395         }
2396     }
2397 }
2398
2399 // Clear out names in file scope.
2400
2401 void
2402 Gogo::clear_file_scope()
2403 {
2404   this->package_->bindings()->clear_file_scope(this);
2405
2406   // Warn about packages which were imported but not used.
2407   bool quiet = saw_errors();
2408   for (Packages::iterator p = this->packages_.begin();
2409        p != this->packages_.end();
2410        ++p)
2411     {
2412       Package* package = p->second;
2413       if (package != this->package_ && !quiet)
2414         {
2415           for (Package::Aliases::const_iterator p1 = package->aliases().begin();
2416                p1 != package->aliases().end();
2417                ++p1)
2418             {
2419               if (!p1->second->used())
2420                 {
2421                   // Give a more refined error message if the alias name is known.
2422                   std::string pkg_name = package->package_name();
2423                   if (p1->first != pkg_name && p1->first[0] != '.')
2424                     {
2425                       go_error_at(p1->second->location(),
2426                                   "imported and not used: %s as %s",
2427                                   Gogo::message_name(pkg_name).c_str(),
2428                                   Gogo::message_name(p1->first).c_str());
2429                     }
2430                   else
2431                     go_error_at(p1->second->location(),
2432                                 "imported and not used: %s",
2433                                 Gogo::message_name(pkg_name).c_str());
2434                 }
2435             }
2436         }
2437       package->clear_used();
2438     }
2439
2440   this->current_file_imported_unsafe_ = false;
2441 }
2442
2443 // Queue up a type specific function for later writing.  These are
2444 // written out in write_specific_type_functions, called after the
2445 // parse tree is lowered.
2446
2447 void
2448 Gogo::queue_specific_type_function(Type* type, Named_type* name, int64_t size,
2449                                    const std::string& hash_name,
2450                                    Function_type* hash_fntype,
2451                                    const std::string& equal_name,
2452                                    Function_type* equal_fntype)
2453 {
2454   go_assert(!this->specific_type_functions_are_written_);
2455   go_assert(!this->in_global_scope());
2456   Specific_type_function* tsf = new Specific_type_function(type, name, size,
2457                                                            hash_name,
2458                                                            hash_fntype,
2459                                                            equal_name,
2460                                                            equal_fntype);
2461   this->specific_type_functions_.push_back(tsf);
2462 }
2463
2464 // Look for types which need specific hash or equality functions.
2465
2466 class Specific_type_functions : public Traverse
2467 {
2468  public:
2469   Specific_type_functions(Gogo* gogo)
2470     : Traverse(traverse_types),
2471       gogo_(gogo)
2472   { }
2473
2474   int
2475   type(Type*);
2476
2477  private:
2478   Gogo* gogo_;
2479 };
2480
2481 int
2482 Specific_type_functions::type(Type* t)
2483 {
2484   Named_object* hash_fn;
2485   Named_object* equal_fn;
2486   switch (t->classification())
2487     {
2488     case Type::TYPE_NAMED:
2489       {
2490         Named_type* nt = t->named_type();
2491         if (t->needs_specific_type_functions(this->gogo_))
2492           t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
2493
2494         // If this is a struct type, we don't want to make functions
2495         // for the unnamed struct.
2496         Type* rt = nt->real_type();
2497         if (rt->struct_type() == NULL)
2498           {
2499             if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2500               return TRAVERSE_EXIT;
2501           }
2502         else
2503           {
2504             // If this type is defined in another package, then we don't
2505             // need to worry about the unexported fields.
2506             bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2507             const Struct_field_list* fields = rt->struct_type()->fields();
2508             for (Struct_field_list::const_iterator p = fields->begin();
2509                  p != fields->end();
2510                  ++p)
2511               {
2512                 if (is_defined_elsewhere
2513                     && Gogo::is_hidden_name(p->field_name()))
2514                   continue;
2515                 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2516                   return TRAVERSE_EXIT;
2517               }
2518           }
2519
2520         return TRAVERSE_SKIP_COMPONENTS;
2521       }
2522
2523     case Type::TYPE_STRUCT:
2524     case Type::TYPE_ARRAY:
2525       if (t->needs_specific_type_functions(this->gogo_))
2526         t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
2527       break;
2528
2529     default:
2530       break;
2531     }
2532
2533   return TRAVERSE_CONTINUE;
2534 }
2535
2536 // Write out type specific functions.
2537
2538 void
2539 Gogo::write_specific_type_functions()
2540 {
2541   Specific_type_functions stf(this);
2542   this->traverse(&stf);
2543
2544   while (!this->specific_type_functions_.empty())
2545     {
2546       Specific_type_function* tsf = this->specific_type_functions_.back();
2547       this->specific_type_functions_.pop_back();
2548       tsf->type->write_specific_type_functions(this, tsf->name, tsf->size,
2549                                                tsf->hash_name,
2550                                                tsf->hash_fntype,
2551                                                tsf->equal_name,
2552                                                tsf->equal_fntype);
2553       delete tsf;
2554     }
2555   this->specific_type_functions_are_written_ = true;
2556 }
2557
2558 // Traverse the tree.
2559
2560 void
2561 Gogo::traverse(Traverse* traverse)
2562 {
2563   // Traverse the current package first for consistency.  The other
2564   // packages will only contain imported types, constants, and
2565   // declarations.
2566   if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2567     return;
2568   for (Packages::const_iterator p = this->packages_.begin();
2569        p != this->packages_.end();
2570        ++p)
2571     {
2572       if (p->second != this->package_)
2573         {
2574           if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2575             break;
2576         }
2577     }
2578 }
2579
2580 // Add a type to verify.  This is used for types of sink variables, in
2581 // order to give appropriate error messages.
2582
2583 void
2584 Gogo::add_type_to_verify(Type* type)
2585 {
2586   this->verify_types_.push_back(type);
2587 }
2588
2589 // Traversal class used to verify types.
2590
2591 class Verify_types : public Traverse
2592 {
2593  public:
2594   Verify_types()
2595     : Traverse(traverse_types)
2596   { }
2597
2598   int
2599   type(Type*);
2600 };
2601
2602 // Verify that a type is correct.
2603
2604 int
2605 Verify_types::type(Type* t)
2606 {
2607   if (!t->verify())
2608     return TRAVERSE_SKIP_COMPONENTS;
2609   return TRAVERSE_CONTINUE;
2610 }
2611
2612 // Verify that all types are correct.
2613
2614 void
2615 Gogo::verify_types()
2616 {
2617   Verify_types traverse;
2618   this->traverse(&traverse);
2619
2620   for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2621        p != this->verify_types_.end();
2622        ++p)
2623     (*p)->verify();
2624   this->verify_types_.clear();
2625 }
2626
2627 // Traversal class used to lower parse tree.
2628
2629 class Lower_parse_tree : public Traverse
2630 {
2631  public:
2632   Lower_parse_tree(Gogo* gogo, Named_object* function)
2633     : Traverse(traverse_variables
2634                | traverse_constants
2635                | traverse_functions
2636                | traverse_statements
2637                | traverse_expressions),
2638       gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2639   { }
2640
2641   void
2642   set_inserter(const Statement_inserter* inserter)
2643   { this->inserter_ = *inserter; }
2644
2645   int
2646   variable(Named_object*);
2647
2648   int
2649   constant(Named_object*, bool);
2650
2651   int
2652   function(Named_object*);
2653
2654   int
2655   statement(Block*, size_t* pindex, Statement*);
2656
2657   int
2658   expression(Expression**);
2659
2660  private:
2661   // General IR.
2662   Gogo* gogo_;
2663   // The function we are traversing.
2664   Named_object* function_;
2665   // Value to use for the predeclared constant iota.
2666   int iota_value_;
2667   // Current statement inserter for use by expressions.
2668   Statement_inserter inserter_;
2669 };
2670
2671 // Lower variables.
2672
2673 int
2674 Lower_parse_tree::variable(Named_object* no)
2675 {
2676   if (!no->is_variable())
2677     return TRAVERSE_CONTINUE;
2678
2679   if (no->is_variable() && no->var_value()->is_global())
2680     {
2681       // Global variables can have loops in their initialization
2682       // expressions.  This is handled in lower_init_expression.
2683       no->var_value()->lower_init_expression(this->gogo_, this->function_,
2684                                              &this->inserter_);
2685       return TRAVERSE_CONTINUE;
2686     }
2687
2688   // This is a local variable.  We are going to return
2689   // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2690   // initialization expression when we reach the variable declaration
2691   // statement.  However, that means that we need to traverse the type
2692   // ourselves.
2693   if (no->var_value()->has_type())
2694     {
2695       Type* type = no->var_value()->type();
2696       if (type != NULL)
2697         {
2698           if (Type::traverse(type, this) == TRAVERSE_EXIT)
2699             return TRAVERSE_EXIT;
2700         }
2701     }
2702   go_assert(!no->var_value()->has_pre_init());
2703
2704   return TRAVERSE_SKIP_COMPONENTS;
2705 }
2706
2707 // Lower constants.  We handle constants specially so that we can set
2708 // the right value for the predeclared constant iota.  This works in
2709 // conjunction with the way we lower Const_expression objects.
2710
2711 int
2712 Lower_parse_tree::constant(Named_object* no, bool)
2713 {
2714   Named_constant* nc = no->const_value();
2715
2716   // Don't get into trouble if the constant's initializer expression
2717   // refers to the constant itself.
2718   if (nc->lowering())
2719     return TRAVERSE_CONTINUE;
2720   nc->set_lowering();
2721
2722   go_assert(this->iota_value_ == -1);
2723   this->iota_value_ = nc->iota_value();
2724   nc->traverse_expression(this);
2725   this->iota_value_ = -1;
2726
2727   nc->clear_lowering();
2728
2729   // We will traverse the expression a second time, but that will be
2730   // fast.
2731
2732   return TRAVERSE_CONTINUE;
2733 }
2734
2735 // Lower the body of a function, and set the closure type.  Record the
2736 // function while lowering it, so that we can pass it down when
2737 // lowering an expression.
2738
2739 int
2740 Lower_parse_tree::function(Named_object* no)
2741 {
2742   no->func_value()->set_closure_type();
2743
2744   go_assert(this->function_ == NULL);
2745   this->function_ = no;
2746   int t = no->func_value()->traverse(this);
2747   this->function_ = NULL;
2748
2749   if (t == TRAVERSE_EXIT)
2750     return t;
2751   return TRAVERSE_SKIP_COMPONENTS;
2752 }
2753
2754 // Lower statement parse trees.
2755
2756 int
2757 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
2758 {
2759   // Because we explicitly traverse the statement's contents
2760   // ourselves, we want to skip block statements here.  There is
2761   // nothing to lower in a block statement.
2762   if (sorig->is_block_statement())
2763     return TRAVERSE_CONTINUE;
2764
2765   Statement_inserter hold_inserter(this->inserter_);
2766   this->inserter_ = Statement_inserter(block, pindex);
2767
2768   // Lower the expressions first.
2769   int t = sorig->traverse_contents(this);
2770   if (t == TRAVERSE_EXIT)
2771     {
2772       this->inserter_ = hold_inserter;
2773       return t;
2774     }
2775
2776   // Keep lowering until nothing changes.
2777   Statement* s = sorig;
2778   while (true)
2779     {
2780       Statement* snew = s->lower(this->gogo_, this->function_, block,
2781                                  &this->inserter_);
2782       if (snew == s)
2783         break;
2784       s = snew;
2785       t = s->traverse_contents(this);
2786       if (t == TRAVERSE_EXIT)
2787         {
2788           this->inserter_ = hold_inserter;
2789           return t;
2790         }
2791     }
2792
2793   if (s != sorig)
2794     block->replace_statement(*pindex, s);
2795
2796   this->inserter_ = hold_inserter;
2797   return TRAVERSE_SKIP_COMPONENTS;
2798 }
2799
2800 // Lower expression parse trees.
2801
2802 int
2803 Lower_parse_tree::expression(Expression** pexpr)
2804 {
2805   // We have to lower all subexpressions first, so that we can get
2806   // their type if necessary.  This is awkward, because we don't have
2807   // a postorder traversal pass.
2808   if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2809     return TRAVERSE_EXIT;
2810   // Keep lowering until nothing changes.
2811   while (true)
2812     {
2813       Expression* e = *pexpr;
2814       Expression* enew = e->lower(this->gogo_, this->function_,
2815                                   &this->inserter_, this->iota_value_);
2816       if (enew == e)
2817         break;
2818       if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
2819         return TRAVERSE_EXIT;
2820       *pexpr = enew;
2821     }
2822   return TRAVERSE_SKIP_COMPONENTS;
2823 }
2824
2825 // Lower the parse tree.  This is called after the parse is complete,
2826 // when all names should be resolved.
2827
2828 void
2829 Gogo::lower_parse_tree()
2830 {
2831   Lower_parse_tree lower_parse_tree(this, NULL);
2832   this->traverse(&lower_parse_tree);
2833
2834   // There might be type definitions that involve expressions such as the
2835   // array length.  Make sure to lower these expressions as well.  Otherwise,
2836   // errors hidden within a type can introduce unexpected errors into later
2837   // passes.
2838   for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2839        p != this->verify_types_.end();
2840        ++p)
2841     Type::traverse(*p, &lower_parse_tree);
2842 }
2843
2844 // Lower a block.
2845
2846 void
2847 Gogo::lower_block(Named_object* function, Block* block)
2848 {
2849   Lower_parse_tree lower_parse_tree(this, function);
2850   block->traverse(&lower_parse_tree);
2851 }
2852
2853 // Lower an expression.  INSERTER may be NULL, in which case the
2854 // expression had better not need to create any temporaries.
2855
2856 void
2857 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
2858                        Expression** pexpr)
2859 {
2860   Lower_parse_tree lower_parse_tree(this, function);
2861   if (inserter != NULL)
2862     lower_parse_tree.set_inserter(inserter);
2863   lower_parse_tree.expression(pexpr);
2864 }
2865
2866 // Lower a constant.  This is called when lowering a reference to a
2867 // constant.  We have to make sure that the constant has already been
2868 // lowered.
2869
2870 void
2871 Gogo::lower_constant(Named_object* no)
2872 {
2873   go_assert(no->is_const());
2874   Lower_parse_tree lower(this, NULL);
2875   lower.constant(no, false);
2876 }
2877
2878 // Traverse the tree to create function descriptors as needed.
2879
2880 class Create_function_descriptors : public Traverse
2881 {
2882  public:
2883   Create_function_descriptors(Gogo* gogo)
2884     : Traverse(traverse_functions | traverse_expressions),
2885       gogo_(gogo)
2886   { }
2887
2888   int
2889   function(Named_object*);
2890
2891   int
2892   expression(Expression**);
2893
2894  private:
2895   Gogo* gogo_;
2896 };
2897
2898 // Create a descriptor for every top-level exported function.
2899
2900 int
2901 Create_function_descriptors::function(Named_object* no)
2902 {
2903   if (no->is_function()
2904       && no->func_value()->enclosing() == NULL
2905       && !no->func_value()->is_method()
2906       && !Gogo::is_hidden_name(no->name())
2907       && !Gogo::is_thunk(no))
2908     no->func_value()->descriptor(this->gogo_, no);
2909
2910   return TRAVERSE_CONTINUE;
2911 }
2912
2913 // If we see a function referenced in any way other than calling it,
2914 // create a descriptor for it.
2915
2916 int
2917 Create_function_descriptors::expression(Expression** pexpr)
2918 {
2919   Expression* expr = *pexpr;
2920
2921   Func_expression* fe = expr->func_expression();
2922   if (fe != NULL)
2923     {
2924       // We would not get here for a call to this function, so this is
2925       // a reference to a function other than calling it.  We need a
2926       // descriptor.
2927       if (fe->closure() != NULL)
2928         return TRAVERSE_CONTINUE;
2929       Named_object* no = fe->named_object();
2930       if (no->is_function() && !no->func_value()->is_method())
2931         no->func_value()->descriptor(this->gogo_, no);
2932       else if (no->is_function_declaration()
2933                && !no->func_declaration_value()->type()->is_method()
2934                && !Linemap::is_predeclared_location(no->location()))
2935         no->func_declaration_value()->descriptor(this->gogo_, no);
2936       return TRAVERSE_CONTINUE;
2937     }
2938
2939   Bound_method_expression* bme = expr->bound_method_expression();
2940   if (bme != NULL)
2941     {
2942       // We would not get here for a call to this method, so this is a
2943       // method value.  We need to create a thunk.
2944       Bound_method_expression::create_thunk(this->gogo_, bme->method(),
2945                                             bme->function());
2946       return TRAVERSE_CONTINUE;
2947     }
2948
2949   Interface_field_reference_expression* ifre =
2950     expr->interface_field_reference_expression();
2951   if (ifre != NULL)
2952     {
2953       // We would not get here for a call to this interface method, so
2954       // this is a method value.  We need to create a thunk.
2955       Interface_type* type = ifre->expr()->type()->interface_type();
2956       if (type != NULL)
2957         Interface_field_reference_expression::create_thunk(this->gogo_, type,
2958                                                            ifre->name());
2959       return TRAVERSE_CONTINUE;
2960     }
2961
2962   Call_expression* ce = expr->call_expression();
2963   if (ce != NULL)
2964     {
2965       Expression* fn = ce->fn();
2966       if (fn->func_expression() != NULL
2967           || fn->bound_method_expression() != NULL
2968           || fn->interface_field_reference_expression() != NULL)
2969         {
2970           // Traverse the arguments but not the function.
2971           Expression_list* args = ce->args();
2972           if (args != NULL)
2973             {
2974               if (args->traverse(this) == TRAVERSE_EXIT)
2975                 return TRAVERSE_EXIT;
2976             }
2977           return TRAVERSE_SKIP_COMPONENTS;
2978         }
2979     }
2980
2981   return TRAVERSE_CONTINUE;
2982 }
2983
2984 // Create function descriptors as needed.  We need a function
2985 // descriptor for all exported functions and for all functions that
2986 // are referenced without being called.
2987
2988 void
2989 Gogo::create_function_descriptors()
2990 {
2991   // Create a function descriptor for any exported function that is
2992   // declared in this package.  This is so that we have a descriptor
2993   // for functions written in assembly.  Gather the descriptors first
2994   // so that we don't add declarations while looping over them.
2995   std::vector<Named_object*> fndecls;
2996   Bindings* b = this->package_->bindings();
2997   for (Bindings::const_declarations_iterator p = b->begin_declarations();
2998        p != b->end_declarations();
2999        ++p)
3000     {
3001       Named_object* no = p->second;
3002       if (no->is_function_declaration()
3003           && !no->func_declaration_value()->type()->is_method()
3004           && !Linemap::is_predeclared_location(no->location())
3005           && !Gogo::is_hidden_name(no->name()))
3006         fndecls.push_back(no);
3007     }
3008   for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
3009        p != fndecls.end();
3010        ++p)
3011     (*p)->func_declaration_value()->descriptor(this, *p);
3012   fndecls.clear();
3013
3014   Create_function_descriptors cfd(this);
3015   this->traverse(&cfd);
3016 }
3017
3018 // Look for interface types to finalize methods of inherited
3019 // interfaces.
3020
3021 class Finalize_methods : public Traverse
3022 {
3023  public:
3024   Finalize_methods(Gogo* gogo)
3025     : Traverse(traverse_types),
3026       gogo_(gogo)
3027   { }
3028
3029   int
3030   type(Type*);
3031
3032  private:
3033   Gogo* gogo_;
3034 };
3035
3036 // Finalize the methods of an interface type.
3037
3038 int
3039 Finalize_methods::type(Type* t)
3040 {
3041   // Check the classification so that we don't finalize the methods
3042   // twice for a named interface type.
3043   switch (t->classification())
3044     {
3045     case Type::TYPE_INTERFACE:
3046       t->interface_type()->finalize_methods();
3047       break;
3048
3049     case Type::TYPE_NAMED:
3050       {
3051         // We have to finalize the methods of the real type first.
3052         // But if the real type is a struct type, then we only want to
3053         // finalize the methods of the field types, not of the struct
3054         // type itself.  We don't want to add methods to the struct,
3055         // since it has a name.
3056         Named_type* nt = t->named_type();
3057         Type* rt = nt->real_type();
3058         if (rt->classification() != Type::TYPE_STRUCT)
3059           {
3060             if (Type::traverse(rt, this) == TRAVERSE_EXIT)
3061               return TRAVERSE_EXIT;
3062           }
3063         else
3064           {
3065             if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3066               return TRAVERSE_EXIT;
3067           }
3068
3069         nt->finalize_methods(this->gogo_);
3070
3071         // If this type is defined in a different package, then finalize the
3072         // types of all the methods, since we won't see them otherwise.
3073         if (nt->named_object()->package() != NULL && nt->has_any_methods())
3074           {
3075             const Methods* methods = nt->methods();
3076             for (Methods::const_iterator p = methods->begin();
3077                  p != methods->end();
3078                  ++p)
3079               {
3080                 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3081                   return TRAVERSE_EXIT;
3082               }
3083           }
3084
3085         // Finalize the types of all methods that are declared but not
3086         // defined, since we won't see the declarations otherwise.
3087         if (nt->named_object()->package() == NULL
3088             && nt->local_methods() != NULL)
3089           {
3090             const Bindings* methods = nt->local_methods();
3091             for (Bindings::const_declarations_iterator p =
3092                    methods->begin_declarations();
3093                  p != methods->end_declarations();
3094                  p++)
3095               {
3096                 if (p->second->is_function_declaration())
3097                   {
3098                     Type* mt = p->second->func_declaration_value()->type();
3099                     if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3100                       return TRAVERSE_EXIT;
3101                   }
3102               }
3103           }
3104
3105         return TRAVERSE_SKIP_COMPONENTS;
3106       }
3107
3108     case Type::TYPE_STRUCT:
3109       // Traverse the field types first in case there is an embedded
3110       // field with methods that the struct should inherit.
3111       if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3112           return TRAVERSE_EXIT;
3113       t->struct_type()->finalize_methods(this->gogo_);
3114       return TRAVERSE_SKIP_COMPONENTS;
3115
3116     default:
3117       break;
3118     }
3119
3120   return TRAVERSE_CONTINUE;
3121 }
3122
3123 // Finalize method lists and build stub methods for types.
3124
3125 void
3126 Gogo::finalize_methods()
3127 {
3128   Finalize_methods finalize(this);
3129   this->traverse(&finalize);
3130 }
3131
3132 // Set types for unspecified variables and constants.
3133
3134 void
3135 Gogo::determine_types()
3136 {
3137   Bindings* bindings = this->current_bindings();
3138   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3139        p != bindings->end_definitions();
3140        ++p)
3141     {
3142       if ((*p)->is_function())
3143         (*p)->func_value()->determine_types();
3144       else if ((*p)->is_variable())
3145         (*p)->var_value()->determine_type();
3146       else if ((*p)->is_const())
3147         (*p)->const_value()->determine_type();
3148
3149       // See if a variable requires us to build an initialization
3150       // function.  We know that we will see all global variables
3151       // here.
3152       if (!this->need_init_fn_ && (*p)->is_variable())
3153         {
3154           Variable* variable = (*p)->var_value();
3155
3156           // If this is a global variable which requires runtime
3157           // initialization, we need an initialization function.
3158           if (!variable->is_global())
3159             ;
3160           else if (variable->init() == NULL)
3161             ;
3162           else if (variable->type()->interface_type() != NULL)
3163             this->need_init_fn_ = true;
3164           else if (variable->init()->is_constant())
3165             ;
3166           else if (!variable->init()->is_composite_literal())
3167             this->need_init_fn_ = true;
3168           else if (variable->init()->is_nonconstant_composite_literal())
3169             this->need_init_fn_ = true;
3170
3171           // If this is a global variable which holds a pointer value,
3172           // then we need an initialization function to register it as a
3173           // GC root.
3174           if (variable->is_global() && variable->type()->has_pointer())
3175             this->need_init_fn_ = true;
3176         }
3177     }
3178
3179   // Determine the types of constants in packages.
3180   for (Packages::const_iterator p = this->packages_.begin();
3181        p != this->packages_.end();
3182        ++p)
3183     p->second->determine_types();
3184 }
3185
3186 // Traversal class used for type checking.
3187
3188 class Check_types_traverse : public Traverse
3189 {
3190  public:
3191   Check_types_traverse(Gogo* gogo)
3192     : Traverse(traverse_variables
3193                | traverse_constants
3194                | traverse_functions
3195                | traverse_statements
3196                | traverse_expressions),
3197       gogo_(gogo)
3198   { }
3199
3200   int
3201   variable(Named_object*);
3202
3203   int
3204   constant(Named_object*, bool);
3205
3206   int
3207   function(Named_object*);
3208
3209   int
3210   statement(Block*, size_t* pindex, Statement*);
3211
3212   int
3213   expression(Expression**);
3214
3215  private:
3216   // General IR.
3217   Gogo* gogo_;
3218 };
3219
3220 // Check that a variable initializer has the right type.
3221
3222 int
3223 Check_types_traverse::variable(Named_object* named_object)
3224 {
3225   if (named_object->is_variable())
3226     {
3227       Variable* var = named_object->var_value();
3228
3229       // Give error if variable type is not defined.
3230       var->type()->base();
3231
3232       Expression* init = var->init();
3233       std::string reason;
3234       if (init != NULL
3235           && !Type::are_assignable(var->type(), init->type(), &reason))
3236         {
3237           if (reason.empty())
3238             go_error_at(var->location(), "incompatible type in initialization");
3239           else
3240             go_error_at(var->location(),
3241                         "incompatible type in initialization (%s)",
3242                         reason.c_str());
3243           init = Expression::make_error(named_object->location());
3244           var->clear_init();
3245         }
3246       else if (init != NULL
3247                && init->func_expression() != NULL)
3248         {
3249           Named_object* no = init->func_expression()->named_object();
3250           Function_type* fntype;
3251           if (no->is_function())
3252             fntype = no->func_value()->type();
3253           else if (no->is_function_declaration())
3254             fntype = no->func_declaration_value()->type();
3255           else
3256             go_unreachable();
3257
3258           // Builtin functions cannot be used as function values for variable
3259           // initialization.
3260           if (fntype->is_builtin())
3261             {
3262               go_error_at(init->location(),
3263                           "invalid use of special builtin function %qs; "
3264                           "must be called",
3265                           no->message_name().c_str());
3266             }
3267         }
3268       if (!var->is_used()
3269           && !var->is_global()
3270           && !var->is_parameter()
3271           && !var->is_receiver()
3272           && !var->type()->is_error()
3273           && (init == NULL || !init->is_error_expression())
3274           && !Lex::is_invalid_identifier(named_object->name()))
3275         go_error_at(var->location(), "%qs declared and not used",
3276                     named_object->message_name().c_str());
3277     }
3278   return TRAVERSE_CONTINUE;
3279 }
3280
3281 // Check that a constant initializer has the right type.
3282
3283 int
3284 Check_types_traverse::constant(Named_object* named_object, bool)
3285 {
3286   Named_constant* constant = named_object->const_value();
3287   Type* ctype = constant->type();
3288   if (ctype->integer_type() == NULL
3289       && ctype->float_type() == NULL
3290       && ctype->complex_type() == NULL
3291       && !ctype->is_boolean_type()
3292       && !ctype->is_string_type())
3293     {
3294       if (ctype->is_nil_type())
3295         go_error_at(constant->location(), "const initializer cannot be nil");
3296       else if (!ctype->is_error())
3297         go_error_at(constant->location(), "invalid constant type");
3298       constant->set_error();
3299     }
3300   else if (!constant->expr()->is_constant())
3301     {
3302       go_error_at(constant->expr()->location(), "expression is not constant");
3303       constant->set_error();
3304     }
3305   else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3306                                  NULL))
3307     {
3308       go_error_at(constant->location(),
3309                   "initialization expression has wrong type");
3310       constant->set_error();
3311     }
3312   return TRAVERSE_CONTINUE;
3313 }
3314
3315 // There are no types to check in a function, but this is where we
3316 // issue warnings about labels which are defined but not referenced.
3317
3318 int
3319 Check_types_traverse::function(Named_object* no)
3320 {
3321   no->func_value()->check_labels();
3322   return TRAVERSE_CONTINUE;
3323 }
3324
3325 // Check that types are valid in a statement.
3326
3327 int
3328 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3329 {
3330   s->check_types(this->gogo_);
3331   return TRAVERSE_CONTINUE;
3332 }
3333
3334 // Check that types are valid in an expression.
3335
3336 int
3337 Check_types_traverse::expression(Expression** expr)
3338 {
3339   (*expr)->check_types(this->gogo_);
3340   return TRAVERSE_CONTINUE;
3341 }
3342
3343 // Check that types are valid.
3344
3345 void
3346 Gogo::check_types()
3347 {
3348   Check_types_traverse traverse(this);
3349   this->traverse(&traverse);
3350
3351   Bindings* bindings = this->current_bindings();
3352   for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3353        p != bindings->end_declarations();
3354        ++p)
3355     {
3356       // Also check the types in a function declaration's signature.
3357       Named_object* no = p->second;
3358       if (no->is_function_declaration())
3359         no->func_declaration_value()->check_types();
3360     }
3361 }
3362
3363 // Check the types in a single block.
3364
3365 void
3366 Gogo::check_types_in_block(Block* block)
3367 {
3368   Check_types_traverse traverse(this);
3369   block->traverse(&traverse);
3370 }
3371
3372 // A traversal class used to find a single shortcut operator within an
3373 // expression.
3374
3375 class Find_shortcut : public Traverse
3376 {
3377  public:
3378   Find_shortcut()
3379     : Traverse(traverse_blocks
3380                | traverse_statements
3381                | traverse_expressions),
3382       found_(NULL)
3383   { }
3384
3385   // A pointer to the expression which was found, or NULL if none was
3386   // found.
3387   Expression**
3388   found() const
3389   { return this->found_; }
3390
3391  protected:
3392   int
3393   block(Block*)
3394   { return TRAVERSE_SKIP_COMPONENTS; }
3395
3396   int
3397   statement(Block*, size_t*, Statement*)
3398   { return TRAVERSE_SKIP_COMPONENTS; }
3399
3400   int
3401   expression(Expression**);
3402
3403  private:
3404   Expression** found_;
3405 };
3406
3407 // Find a shortcut expression.
3408
3409 int
3410 Find_shortcut::expression(Expression** pexpr)
3411 {
3412   Expression* expr = *pexpr;
3413   Binary_expression* be = expr->binary_expression();
3414   if (be == NULL)
3415     return TRAVERSE_CONTINUE;
3416   Operator op = be->op();
3417   if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
3418     return TRAVERSE_CONTINUE;
3419   go_assert(this->found_ == NULL);
3420   this->found_ = pexpr;
3421   return TRAVERSE_EXIT;
3422 }
3423
3424 // A traversal class used to turn shortcut operators into explicit if
3425 // statements.
3426
3427 class Shortcuts : public Traverse
3428 {
3429  public:
3430   Shortcuts(Gogo* gogo)
3431     : Traverse(traverse_variables
3432                | traverse_statements),
3433       gogo_(gogo)
3434   { }
3435
3436  protected:
3437   int
3438   variable(Named_object*);
3439
3440   int
3441   statement(Block*, size_t*, Statement*);
3442
3443  private:
3444   // Convert a shortcut operator.
3445   Statement*
3446   convert_shortcut(Block* enclosing, Expression** pshortcut);
3447
3448   // The IR.
3449   Gogo* gogo_;
3450 };
3451
3452 // Remove shortcut operators in a single statement.
3453
3454 int
3455 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
3456 {
3457   // FIXME: This approach doesn't work for switch statements, because
3458   // we add the new statements before the whole switch when we need to
3459   // instead add them just before the switch expression.  The right
3460   // fix is probably to lower switch statements with nonconstant cases
3461   // to a series of conditionals.
3462   if (s->switch_statement() != NULL)
3463     return TRAVERSE_CONTINUE;
3464
3465   while (true)
3466     {
3467       Find_shortcut find_shortcut;
3468
3469       // If S is a variable declaration, then ordinary traversal won't
3470       // do anything.  We want to explicitly traverse the
3471       // initialization expression if there is one.
3472       Variable_declaration_statement* vds = s->variable_declaration_statement();
3473       Expression* init = NULL;
3474       if (vds == NULL)
3475         s->traverse_contents(&find_shortcut);
3476       else
3477         {
3478           init = vds->var()->var_value()->init();
3479           if (init == NULL)
3480             return TRAVERSE_CONTINUE;
3481           init->traverse(&init, &find_shortcut);
3482         }
3483       Expression** pshortcut = find_shortcut.found();
3484       if (pshortcut == NULL)
3485         return TRAVERSE_CONTINUE;
3486
3487       Statement* snew = this->convert_shortcut(block, pshortcut);
3488       block->insert_statement_before(*pindex, snew);
3489       ++*pindex;
3490
3491       if (pshortcut == &init)
3492         vds->var()->var_value()->set_init(init);
3493     }
3494 }
3495
3496 // Remove shortcut operators in the initializer of a global variable.
3497
3498 int
3499 Shortcuts::variable(Named_object* no)
3500 {
3501   if (no->is_result_variable())
3502     return TRAVERSE_CONTINUE;
3503   Variable* var = no->var_value();
3504   Expression* init = var->init();
3505   if (!var->is_global() || init == NULL)
3506     return TRAVERSE_CONTINUE;
3507
3508   while (true)
3509     {
3510       Find_shortcut find_shortcut;
3511       init->traverse(&init, &find_shortcut);
3512       Expression** pshortcut = find_shortcut.found();
3513       if (pshortcut == NULL)
3514         return TRAVERSE_CONTINUE;
3515
3516       Statement* snew = this->convert_shortcut(NULL, pshortcut);
3517       var->add_preinit_statement(this->gogo_, snew);
3518       if (pshortcut == &init)
3519         var->set_init(init);
3520     }
3521 }
3522
3523 // Given an expression which uses a shortcut operator, return a
3524 // statement which implements it, and update *PSHORTCUT accordingly.
3525
3526 Statement*
3527 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
3528 {
3529   Binary_expression* shortcut = (*pshortcut)->binary_expression();
3530   Expression* left = shortcut->left();
3531   Expression* right = shortcut->right();
3532   Location loc = shortcut->location();
3533
3534   Block* retblock = new Block(enclosing, loc);
3535   retblock->set_end_location(loc);
3536
3537   Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
3538                                                       left, loc);
3539   retblock->add_statement(ts);
3540
3541   Block* block = new Block(retblock, loc);
3542   block->set_end_location(loc);
3543   Expression* tmpref = Expression::make_temporary_reference(ts, loc);
3544   Statement* assign = Statement::make_assignment(tmpref, right, loc);
3545   block->add_statement(assign);
3546
3547   Expression* cond = Expression::make_temporary_reference(ts, loc);
3548   if (shortcut->binary_expression()->op() == OPERATOR_OROR)
3549     cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3550
3551   Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
3552                                                          loc);
3553   retblock->add_statement(if_statement);
3554
3555   *pshortcut = Expression::make_temporary_reference(ts, loc);
3556
3557   delete shortcut;
3558
3559   // Now convert any shortcut operators in LEFT and RIGHT.
3560   Shortcuts shortcuts(this->gogo_);
3561   retblock->traverse(&shortcuts);
3562
3563   return Statement::make_block_statement(retblock, loc);
3564 }
3565
3566 // Turn shortcut operators into explicit if statements.  Doing this
3567 // considerably simplifies the order of evaluation rules.
3568
3569 void
3570 Gogo::remove_shortcuts()
3571 {
3572   Shortcuts shortcuts(this);
3573   this->traverse(&shortcuts);
3574 }
3575
3576 // A traversal class which finds all the expressions which must be
3577 // evaluated in order within a statement or larger expression.  This
3578 // is used to implement the rules about order of evaluation.
3579
3580 class Find_eval_ordering : public Traverse
3581 {
3582  private:
3583   typedef std::vector<Expression**> Expression_pointers;
3584
3585  public:
3586   Find_eval_ordering()
3587     : Traverse(traverse_blocks
3588                | traverse_statements
3589                | traverse_expressions),
3590       exprs_()
3591   { }
3592
3593   size_t
3594   size() const
3595   { return this->exprs_.size(); }
3596
3597   typedef Expression_pointers::const_iterator const_iterator;
3598
3599   const_iterator
3600   begin() const
3601   { return this->exprs_.begin(); }
3602
3603   const_iterator
3604   end() const
3605   { return this->exprs_.end(); }
3606
3607  protected:
3608   int
3609   block(Block*)
3610   { return TRAVERSE_SKIP_COMPONENTS; }
3611
3612   int
3613   statement(Block*, size_t*, Statement*)
3614   { return TRAVERSE_SKIP_COMPONENTS; }
3615
3616   int
3617   expression(Expression**);
3618
3619  private:
3620   // A list of pointers to expressions with side-effects.
3621   Expression_pointers exprs_;
3622 };
3623
3624 // If an expression must be evaluated in order, put it on the list.
3625
3626 int
3627 Find_eval_ordering::expression(Expression** expression_pointer)
3628 {
3629   // We have to look at subexpressions before this one.
3630   if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3631     return TRAVERSE_EXIT;
3632   if ((*expression_pointer)->must_eval_in_order())
3633     this->exprs_.push_back(expression_pointer);
3634   return TRAVERSE_SKIP_COMPONENTS;
3635 }
3636
3637 // A traversal class for ordering evaluations.
3638
3639 class Order_eval : public Traverse
3640 {
3641  public:
3642   Order_eval(Gogo* gogo)
3643     : Traverse(traverse_variables
3644                | traverse_statements),
3645       gogo_(gogo)
3646   { }
3647
3648   int
3649   variable(Named_object*);
3650
3651   int
3652   statement(Block*, size_t*, Statement*);
3653
3654  private:
3655   // The IR.
3656   Gogo* gogo_;
3657 };
3658
3659 // Implement the order of evaluation rules for a statement.
3660
3661 int
3662 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3663 {
3664   // FIXME: This approach doesn't work for switch statements, because
3665   // we add the new statements before the whole switch when we need to
3666   // instead add them just before the switch expression.  The right
3667   // fix is probably to lower switch statements with nonconstant cases
3668   // to a series of conditionals.
3669   if (stmt->switch_statement() != NULL)
3670     return TRAVERSE_CONTINUE;
3671
3672   Find_eval_ordering find_eval_ordering;
3673
3674   // If S is a variable declaration, then ordinary traversal won't do
3675   // anything.  We want to explicitly traverse the initialization
3676   // expression if there is one.
3677   Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3678   Expression* init = NULL;
3679   Expression* orig_init = NULL;
3680   if (vds == NULL)
3681     stmt->traverse_contents(&find_eval_ordering);
3682   else
3683     {
3684       init = vds->var()->var_value()->init();
3685       if (init == NULL)
3686         return TRAVERSE_CONTINUE;
3687       orig_init = init;
3688
3689       // It might seem that this could be
3690       // init->traverse_subexpressions.  Unfortunately that can fail
3691       // in a case like
3692       //   var err os.Error
3693       //   newvar, err := call(arg())
3694       // Here newvar will have an init of call result 0 of
3695       // call(arg()).  If we only traverse subexpressions, we will
3696       // only find arg(), and we won't bother to move anything out.
3697       // Then we get to the assignment to err, we will traverse the
3698       // whole statement, and this time we will find both call() and
3699       // arg(), and so we will move them out.  This will cause them to
3700       // be put into temporary variables before the assignment to err
3701       // but after the declaration of newvar.  To avoid that problem,
3702       // we traverse the entire expression here.
3703       Expression::traverse(&init, &find_eval_ordering);
3704     }
3705
3706   size_t c = find_eval_ordering.size();
3707   if (c == 0)
3708     return TRAVERSE_CONTINUE;
3709
3710   // If there is only one expression with a side-effect, we can
3711   // usually leave it in place.
3712   if (c == 1)
3713     {
3714       switch (stmt->classification())
3715         {
3716         case Statement::STATEMENT_ASSIGNMENT:
3717           // For an assignment statement, we need to evaluate an
3718           // expression on the right hand side before we evaluate any
3719           // index expression on the left hand side, so for that case
3720           // we always move the expression.  Otherwise we mishandle
3721           // m[0] = len(m) where m is a map.
3722           break;
3723
3724         case Statement::STATEMENT_EXPRESSION:
3725           {
3726             // If this is a call statement that doesn't return any
3727             // values, it will not have been counted as a value to
3728             // move.  We need to move any subexpressions in case they
3729             // are themselves call statements that require passing a
3730             // closure.
3731             Expression* expr = stmt->expression_statement()->expr();
3732             if (expr->call_expression() != NULL
3733                 && expr->call_expression()->result_count() == 0)
3734               break;
3735             return TRAVERSE_CONTINUE;
3736           }
3737
3738         default:
3739           // We can leave the expression in place.
3740           return TRAVERSE_CONTINUE;
3741         }
3742     }
3743
3744   bool is_thunk = stmt->thunk_statement() != NULL;
3745   Expression_statement* es = stmt->expression_statement();
3746   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3747        p != find_eval_ordering.end();
3748        ++p)
3749     {
3750       Expression** pexpr = *p;
3751
3752       // The last expression in a thunk will be the call passed to go
3753       // or defer, which we must not evaluate early.
3754       if (is_thunk && p + 1 == find_eval_ordering.end())
3755         break;
3756
3757       Location loc = (*pexpr)->location();
3758       Statement* s;
3759       if ((*pexpr)->call_expression() == NULL
3760           || (*pexpr)->call_expression()->result_count() < 2)
3761         {
3762           Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3763                                                               loc);
3764           s = ts;
3765           *pexpr = Expression::make_temporary_reference(ts, loc);
3766         }
3767       else
3768         {
3769           // A call expression which returns multiple results needs to
3770           // be handled specially.  We can't create a temporary
3771           // because there is no type to give it.  Any actual uses of
3772           // the values will be done via Call_result_expressions.
3773           //
3774           // Since a given call expression can be shared by multiple
3775           // Call_result_expressions, avoid hoisting the call the
3776           // second time we see it here. In addition, don't try to
3777           // hoist the top-level multi-return call in the statement,
3778           // since doing this would result a tree with more than one copy
3779           // of the call.
3780           if (this->remember_expression(*pexpr))
3781             s = NULL;
3782           else if (es != NULL && *pexpr == es->expr())
3783             s = NULL;
3784           else
3785             s = Statement::make_statement(*pexpr, true);
3786         }
3787
3788       if (s != NULL)
3789         {
3790           block->insert_statement_before(*pindex, s);
3791           ++*pindex;
3792         }
3793     }
3794
3795   if (init != orig_init)
3796     vds->var()->var_value()->set_init(init);
3797
3798   return TRAVERSE_CONTINUE;
3799 }
3800
3801 // Implement the order of evaluation rules for the initializer of a
3802 // global variable.
3803
3804 int
3805 Order_eval::variable(Named_object* no)
3806 {
3807   if (no->is_result_variable())
3808     return TRAVERSE_CONTINUE;
3809   Variable* var = no->var_value();
3810   Expression* init = var->init();
3811   if (!var->is_global() || init == NULL)
3812     return TRAVERSE_CONTINUE;
3813
3814   Find_eval_ordering find_eval_ordering;
3815   Expression::traverse(&init, &find_eval_ordering);
3816
3817   if (find_eval_ordering.size() <= 1)
3818     {
3819       // If there is only one expression with a side-effect, we can
3820       // leave it in place.
3821       return TRAVERSE_SKIP_COMPONENTS;
3822     }
3823
3824   Expression* orig_init = init;
3825
3826   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3827        p != find_eval_ordering.end();
3828        ++p)
3829     {
3830       Expression** pexpr = *p;
3831       Location loc = (*pexpr)->location();
3832       Statement* s;
3833       if ((*pexpr)->call_expression() == NULL
3834           || (*pexpr)->call_expression()->result_count() < 2)
3835         {
3836           Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3837                                                               loc);
3838           s = ts;
3839           *pexpr = Expression::make_temporary_reference(ts, loc);
3840         }
3841       else
3842         {
3843           // A call expression which returns multiple results needs to
3844           // be handled specially.
3845           s = Statement::make_statement(*pexpr, true);
3846         }
3847       var->add_preinit_statement(this->gogo_, s);
3848     }
3849
3850   if (init != orig_init)
3851     var->set_init(init);
3852
3853   return TRAVERSE_SKIP_COMPONENTS;
3854 }
3855
3856 // Use temporary variables to implement the order of evaluation rules.
3857
3858 void
3859 Gogo::order_evaluations()
3860 {
3861   Order_eval order_eval(this);
3862   this->traverse(&order_eval);
3863 }
3864
3865 // Traversal to flatten parse tree after order of evaluation rules are applied.
3866
3867 class Flatten : public Traverse
3868 {
3869  public:
3870   Flatten(Gogo* gogo, Named_object* function)
3871     : Traverse(traverse_variables
3872                | traverse_functions
3873                | traverse_statements
3874                | traverse_expressions),
3875       gogo_(gogo), function_(function), inserter_()
3876   { }
3877
3878   void
3879   set_inserter(const Statement_inserter* inserter)
3880   { this->inserter_ = *inserter; }
3881
3882   int
3883   variable(Named_object*);
3884
3885   int
3886   function(Named_object*);
3887
3888   int
3889   statement(Block*, size_t* pindex, Statement*);
3890
3891   int
3892   expression(Expression**);
3893
3894  private:
3895   // General IR.
3896   Gogo* gogo_;
3897   // The function we are traversing.
3898   Named_object* function_;
3899   // Current statement inserter for use by expressions.
3900   Statement_inserter inserter_;
3901 };
3902
3903 // Flatten variables.
3904
3905 int
3906 Flatten::variable(Named_object* no)
3907 {
3908   if (!no->is_variable())
3909     return TRAVERSE_CONTINUE;
3910
3911   if (no->is_variable() && no->var_value()->is_global())
3912     {
3913       // Global variables can have loops in their initialization
3914       // expressions.  This is handled in flatten_init_expression.
3915       no->var_value()->flatten_init_expression(this->gogo_, this->function_,
3916                                                &this->inserter_);
3917       return TRAVERSE_CONTINUE;
3918     }
3919
3920   go_assert(!no->var_value()->has_pre_init());
3921
3922   return TRAVERSE_SKIP_COMPONENTS;
3923 }
3924
3925 // Flatten the body of a function.  Record the function while flattening it,
3926 // so that we can pass it down when flattening an expression.
3927
3928 int
3929 Flatten::function(Named_object* no)
3930 {
3931   go_assert(this->function_ == NULL);
3932   this->function_ = no;
3933   int t = no->func_value()->traverse(this);
3934   this->function_ = NULL;
3935
3936   if (t == TRAVERSE_EXIT)
3937     return t;
3938   return TRAVERSE_SKIP_COMPONENTS;
3939 }
3940
3941 // Flatten statement parse trees.
3942
3943 int
3944 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
3945 {
3946   // Because we explicitly traverse the statement's contents
3947   // ourselves, we want to skip block statements here.  There is
3948   // nothing to flatten in a block statement.
3949   if (sorig->is_block_statement())
3950     return TRAVERSE_CONTINUE;
3951
3952   Statement_inserter hold_inserter(this->inserter_);
3953   this->inserter_ = Statement_inserter(block, pindex);
3954
3955   // Flatten the expressions first.
3956   int t = sorig->traverse_contents(this);
3957   if (t == TRAVERSE_EXIT)
3958     {
3959       this->inserter_ = hold_inserter;
3960       return t;
3961     }
3962
3963   // Keep flattening until nothing changes.
3964   Statement* s = sorig;
3965   while (true)
3966     {
3967       Statement* snew = s->flatten(this->gogo_, this->function_, block,
3968                                    &this->inserter_);
3969       if (snew == s)
3970         break;
3971       s = snew;
3972       t = s->traverse_contents(this);
3973       if (t == TRAVERSE_EXIT)
3974         {
3975           this->inserter_ = hold_inserter;
3976           return t;
3977         }
3978     }
3979
3980   if (s != sorig)
3981     block->replace_statement(*pindex, s);
3982
3983   this->inserter_ = hold_inserter;
3984   return TRAVERSE_SKIP_COMPONENTS;
3985 }
3986
3987 // Flatten expression parse trees.
3988
3989 int
3990 Flatten::expression(Expression** pexpr)
3991 {
3992   // Keep flattening until nothing changes.
3993   while (true)
3994     {
3995       Expression* e = *pexpr;
3996       if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
3997         return TRAVERSE_EXIT;
3998
3999       Expression* enew = e->flatten(this->gogo_, this->function_,
4000                                     &this->inserter_);
4001       if (enew == e)
4002         break;
4003       *pexpr = enew;
4004     }
4005   return TRAVERSE_SKIP_COMPONENTS;
4006 }
4007
4008 // Flatten a block.
4009
4010 void
4011 Gogo::flatten_block(Named_object* function, Block* block)
4012 {
4013   Flatten flatten(this, function);
4014   block->traverse(&flatten);
4015 }
4016
4017 // Flatten an expression.  INSERTER may be NULL, in which case the
4018 // expression had better not need to create any temporaries.
4019
4020 void
4021 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
4022                          Expression** pexpr)
4023 {
4024   Flatten flatten(this, function);
4025   if (inserter != NULL)
4026     flatten.set_inserter(inserter);
4027   flatten.expression(pexpr);
4028 }
4029
4030 void
4031 Gogo::flatten()
4032 {
4033   Flatten flatten(this, NULL);
4034   this->traverse(&flatten);
4035 }
4036
4037 // Traversal to convert calls to the predeclared recover function to
4038 // pass in an argument indicating whether it can recover from a panic
4039 // or not.
4040
4041 class Convert_recover : public Traverse
4042 {
4043  public:
4044   Convert_recover(Named_object* arg)
4045     : Traverse(traverse_expressions),
4046       arg_(arg)
4047   { }
4048
4049  protected:
4050   int
4051   expression(Expression**);
4052
4053  private:
4054   // The argument to pass to the function.
4055   Named_object* arg_;
4056 };
4057
4058 // Convert calls to recover.
4059
4060 int
4061 Convert_recover::expression(Expression** pp)
4062 {
4063   Call_expression* ce = (*pp)->call_expression();
4064   if (ce != NULL && ce->is_recover_call())
4065     ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4066                                                        ce->location()));
4067   return TRAVERSE_CONTINUE;
4068 }
4069
4070 // Traversal for build_recover_thunks.
4071
4072 class Build_recover_thunks : public Traverse
4073 {
4074  public:
4075   Build_recover_thunks(Gogo* gogo)
4076     : Traverse(traverse_functions),
4077       gogo_(gogo)
4078   { }
4079
4080   int
4081   function(Named_object*);
4082
4083  private:
4084   Expression*
4085   can_recover_arg(Location);
4086
4087   // General IR.
4088   Gogo* gogo_;
4089 };
4090
4091 // If this function calls recover, turn it into a thunk.
4092
4093 int
4094 Build_recover_thunks::function(Named_object* orig_no)
4095 {
4096   Function* orig_func = orig_no->func_value();
4097   if (!orig_func->calls_recover()
4098       || orig_func->is_recover_thunk()
4099       || orig_func->has_recover_thunk())
4100     return TRAVERSE_CONTINUE;
4101
4102   Gogo* gogo = this->gogo_;
4103   Location location = orig_func->location();
4104
4105   static int count;
4106   char buf[50];
4107
4108   Function_type* orig_fntype = orig_func->type();
4109   Typed_identifier_list* new_params = new Typed_identifier_list();
4110   std::string receiver_name;
4111   if (orig_fntype->is_method())
4112     {
4113       const Typed_identifier* receiver = orig_fntype->receiver();
4114       snprintf(buf, sizeof buf, "rt.%u", count);
4115       ++count;
4116       receiver_name = buf;
4117       new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4118                                              receiver->location()));
4119     }
4120   const Typed_identifier_list* orig_params = orig_fntype->parameters();
4121   if (orig_params != NULL && !orig_params->empty())
4122     {
4123       for (Typed_identifier_list::const_iterator p = orig_params->begin();
4124            p != orig_params->end();
4125            ++p)
4126         {
4127           snprintf(buf, sizeof buf, "pt.%u", count);
4128           ++count;
4129           new_params->push_back(Typed_identifier(buf, p->type(),
4130                                                  p->location()));
4131         }
4132     }
4133   snprintf(buf, sizeof buf, "pr.%u", count);
4134   ++count;
4135   std::string can_recover_name = buf;
4136   new_params->push_back(Typed_identifier(can_recover_name,
4137                                          Type::lookup_bool_type(),
4138                                          orig_fntype->location()));
4139
4140   const Typed_identifier_list* orig_results = orig_fntype->results();
4141   Typed_identifier_list* new_results;
4142   if (orig_results == NULL || orig_results->empty())
4143     new_results = NULL;
4144   else
4145     {
4146       new_results = new Typed_identifier_list();
4147       for (Typed_identifier_list::const_iterator p = orig_results->begin();
4148            p != orig_results->end();
4149            ++p)
4150         new_results->push_back(Typed_identifier("", p->type(), p->location()));
4151     }
4152
4153   Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4154                                                        new_results,
4155                                                        orig_fntype->location());
4156   if (orig_fntype->is_varargs())
4157     new_fntype->set_is_varargs();
4158
4159   std::string name = orig_no->name();
4160   if (orig_fntype->is_method())
4161     name += "$" + orig_fntype->receiver()->type()->mangled_name(gogo);
4162   name += "$recover";
4163   Named_object *new_no = gogo->start_function(name, new_fntype, false,
4164                                               location);
4165   Function *new_func = new_no->func_value();
4166   if (orig_func->enclosing() != NULL)
4167     new_func->set_enclosing(orig_func->enclosing());
4168
4169   // We build the code for the original function attached to the new
4170   // function, and then swap the original and new function bodies.
4171   // This means that existing references to the original function will
4172   // then refer to the new function.  That makes this code a little
4173   // confusing, in that the reference to NEW_NO really refers to the
4174   // other function, not the one we are building.
4175
4176   Expression* closure = NULL;
4177   if (orig_func->needs_closure())
4178     {
4179       // For the new function we are creating, declare a new parameter
4180       // variable NEW_CLOSURE_NO and set it to be the closure variable
4181       // of the function.  This will be set to the closure value
4182       // passed in by the caller.  Then pass a reference to this
4183       // variable as the closure value when calling the original
4184       // function.  In other words, simply pass the closure value
4185       // through the thunk we are creating.
4186       Named_object* orig_closure_no = orig_func->closure_var();
4187       Variable* orig_closure_var = orig_closure_no->var_value();
4188       Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4189                                        false, false, location);
4190       new_var->set_is_closure();
4191       snprintf(buf, sizeof buf, "closure.%u", count);
4192       ++count;
4193       Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4194                                                                  new_var);
4195       new_func->set_closure_var(new_closure_no);
4196       closure = Expression::make_var_reference(new_closure_no, location);
4197     }
4198
4199   Expression* fn = Expression::make_func_reference(new_no, closure, location);
4200
4201   Expression_list* args = new Expression_list();
4202   if (new_params != NULL)
4203     {
4204       // Note that we skip the last parameter, which is the boolean
4205       // indicating whether recover can succed.
4206       for (Typed_identifier_list::const_iterator p = new_params->begin();
4207            p + 1 != new_params->end();
4208            ++p)
4209         {
4210           Named_object* p_no = gogo->lookup(p->name(), NULL);
4211           go_assert(p_no != NULL
4212                      && p_no->is_variable()
4213                      && p_no->var_value()->is_parameter());
4214           args->push_back(Expression::make_var_reference(p_no, location));
4215         }
4216     }
4217   args->push_back(this->can_recover_arg(location));
4218
4219   gogo->start_block(location);
4220
4221   Call_expression* call = Expression::make_call(fn, args, false, location);
4222
4223   // Any varargs call has already been lowered.
4224   call->set_varargs_are_lowered();
4225
4226   Statement* s = Statement::make_return_from_call(call, location);
4227   s->determine_types();
4228   gogo->add_statement(s);
4229
4230   Block* b = gogo->finish_block(location);
4231
4232   gogo->add_block(b, location);
4233
4234   // Lower the call in case it returns multiple results.
4235   gogo->lower_block(new_no, b);
4236
4237   gogo->finish_function(location);
4238
4239   // Swap the function bodies and types.
4240   new_func->swap_for_recover(orig_func);
4241   orig_func->set_is_recover_thunk();
4242   new_func->set_calls_recover();
4243   new_func->set_has_recover_thunk();
4244
4245   Bindings* orig_bindings = orig_func->block()->bindings();
4246   Bindings* new_bindings = new_func->block()->bindings();
4247   if (orig_fntype->is_method())
4248     {
4249       // We changed the receiver to be a regular parameter.  We have
4250       // to update the binding accordingly in both functions.
4251       Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4252       go_assert(orig_rec_no != NULL
4253                  && orig_rec_no->is_variable()
4254                  && !orig_rec_no->var_value()->is_receiver());
4255       orig_rec_no->var_value()->set_is_receiver();
4256
4257       std::string new_receiver_name(orig_fntype->receiver()->name());
4258       if (new_receiver_name.empty())
4259         {
4260           // Find the receiver.  It was named "r.NNN" in
4261           // Gogo::start_function.
4262           for (Bindings::const_definitions_iterator p =
4263                  new_bindings->begin_definitions();
4264                p != new_bindings->end_definitions();
4265                ++p)
4266             {
4267               const std::string& pname((*p)->name());
4268               if (pname[0] == 'r' && pname[1] == '.')
4269                 {
4270                   new_receiver_name = pname;
4271                   break;
4272                 }
4273             }
4274           go_assert(!new_receiver_name.empty());
4275         }
4276       Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4277       if (new_rec_no == NULL)
4278         go_assert(saw_errors());
4279       else
4280         {
4281           go_assert(new_rec_no->is_variable()
4282                      && new_rec_no->var_value()->is_receiver());
4283           new_rec_no->var_value()->set_is_not_receiver();
4284         }
4285     }
4286
4287   // Because we flipped blocks but not types, the can_recover
4288   // parameter appears in the (now) old bindings as a parameter.
4289   // Change it to a local variable, whereupon it will be discarded.
4290   Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4291   go_assert(can_recover_no != NULL
4292              && can_recover_no->is_variable()
4293              && can_recover_no->var_value()->is_parameter());
4294   orig_bindings->remove_binding(can_recover_no);
4295
4296   // Add the can_recover argument to the (now) new bindings, and
4297   // attach it to any recover statements.
4298   Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4299                                            false, true, false, location);
4300   can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4301                                               can_recover_var);
4302   Convert_recover convert_recover(can_recover_no);
4303   new_func->traverse(&convert_recover);
4304
4305   // Update the function pointers in any named results.
4306   new_func->update_result_variables();
4307   orig_func->update_result_variables();
4308
4309   return TRAVERSE_CONTINUE;
4310 }
4311
4312 // Return the expression to pass for the .can_recover parameter to the
4313 // new function.  This indicates whether a call to recover may return
4314 // non-nil.  The expression is runtime.canrecover(__builtin_return_address()).
4315
4316 Expression*
4317 Build_recover_thunks::can_recover_arg(Location location)
4318 {
4319   static Named_object* builtin_return_address;
4320   if (builtin_return_address == NULL)
4321     builtin_return_address =
4322       Gogo::declare_builtin_rf_address("__builtin_return_address");
4323
4324   static Named_object* can_recover;
4325   if (can_recover == NULL)
4326     {
4327       const Location bloc = Linemap::predeclared_location();
4328       Typed_identifier_list* param_types = new Typed_identifier_list();
4329       Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4330       param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
4331       Type* boolean_type = Type::lookup_bool_type();
4332       Typed_identifier_list* results = new Typed_identifier_list();
4333       results->push_back(Typed_identifier("", boolean_type, bloc));
4334       Function_type* fntype = Type::make_function_type(NULL, param_types,
4335                                                        results, bloc);
4336       can_recover =
4337         Named_object::make_function_declaration("runtime_canrecover",
4338                                                 NULL, fntype, bloc);
4339       can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4340     }
4341
4342   Expression* fn = Expression::make_func_reference(builtin_return_address,
4343                                                    NULL, location);
4344
4345   Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4346   Expression_list *args = new Expression_list();
4347   args->push_back(zexpr);
4348
4349   Expression* call = Expression::make_call(fn, args, false, location);
4350
4351   args = new Expression_list();
4352   args->push_back(call);
4353
4354   fn = Expression::make_func_reference(can_recover, NULL, location);
4355   return Expression::make_call(fn, args, false, location);
4356 }
4357
4358 // Build thunks for functions which call recover.  We build a new
4359 // function with an extra parameter, which is whether a call to
4360 // recover can succeed.  We then move the body of this function to
4361 // that one.  We then turn this function into a thunk which calls the
4362 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4363 // The function will be marked as not splitting the stack.  This will
4364 // cooperate with the implementation of defer to make recover do the
4365 // right thing.
4366
4367 void
4368 Gogo::build_recover_thunks()
4369 {
4370   Build_recover_thunks build_recover_thunks(this);
4371   this->traverse(&build_recover_thunks);
4372 }
4373
4374 // Return a declaration for __builtin_return_address or
4375 // __builtin_frame_address.
4376
4377 Named_object*
4378 Gogo::declare_builtin_rf_address(const char* name)
4379 {
4380   const Location bloc = Linemap::predeclared_location();
4381
4382   Typed_identifier_list* param_types = new Typed_identifier_list();
4383   Type* uint32_type = Type::lookup_integer_type("uint32");
4384   param_types->push_back(Typed_identifier("l", uint32_type, bloc));
4385
4386   Typed_identifier_list* return_types = new Typed_identifier_list();
4387   Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4388   return_types->push_back(Typed_identifier("", voidptr_type, bloc));
4389
4390   Function_type* fntype = Type::make_function_type(NULL, param_types,
4391                                                    return_types, bloc);
4392   Named_object* ret = Named_object::make_function_declaration(name, NULL,
4393                                                               fntype, bloc);
4394   ret->func_declaration_value()->set_asm_name(name);
4395   return ret;
4396 }
4397
4398 // Build a call to the runtime error function.
4399
4400 Expression*
4401 Gogo::runtime_error(int code, Location location)
4402 {
4403   Type* int32_type = Type::lookup_integer_type("int32");
4404   Expression* code_expr = Expression::make_integer_ul(code, int32_type,
4405                                                       location);
4406   return Runtime::make_call(Runtime::RUNTIME_ERROR, location, 1, code_expr);
4407 }
4408
4409 // Look for named types to see whether we need to create an interface
4410 // method table.
4411
4412 class Build_method_tables : public Traverse
4413 {
4414  public:
4415   Build_method_tables(Gogo* gogo,
4416                       const std::vector<Interface_type*>& interfaces)
4417     : Traverse(traverse_types),
4418       gogo_(gogo), interfaces_(interfaces)
4419   { }
4420
4421   int
4422   type(Type*);
4423
4424  private:
4425   // The IR.
4426   Gogo* gogo_;
4427   // A list of locally defined interfaces which have hidden methods.
4428   const std::vector<Interface_type*>& interfaces_;
4429 };
4430
4431 // Build all required interface method tables for types.  We need to
4432 // ensure that we have an interface method table for every interface
4433 // which has a hidden method, for every named type which implements
4434 // that interface.  Normally we can just build interface method tables
4435 // as we need them.  However, in some cases we can require an
4436 // interface method table for an interface defined in a different
4437 // package for a type defined in that package.  If that interface and
4438 // type both use a hidden method, that is OK.  However, we will not be
4439 // able to build that interface method table when we need it, because
4440 // the type's hidden method will be static.  So we have to build it
4441 // here, and just refer it from other packages as needed.
4442
4443 void
4444 Gogo::build_interface_method_tables()
4445 {
4446   if (saw_errors())
4447     return;
4448
4449   std::vector<Interface_type*> hidden_interfaces;
4450   hidden_interfaces.reserve(this->interface_types_.size());
4451   for (std::vector<Interface_type*>::const_iterator pi =
4452          this->interface_types_.begin();
4453        pi != this->interface_types_.end();
4454        ++pi)
4455     {
4456       const Typed_identifier_list* methods = (*pi)->methods();
4457       if (methods == NULL)
4458         continue;
4459       for (Typed_identifier_list::const_iterator pm = methods->begin();
4460            pm != methods->end();
4461            ++pm)
4462         {
4463           if (Gogo::is_hidden_name(pm->name()))
4464             {
4465               hidden_interfaces.push_back(*pi);
4466               break;
4467             }
4468         }
4469     }
4470
4471   if (!hidden_interfaces.empty())
4472     {
4473       // Now traverse the tree looking for all named types.
4474       Build_method_tables bmt(this, hidden_interfaces);
4475       this->traverse(&bmt);
4476     }
4477
4478   // We no longer need the list of interfaces.
4479
4480   this->interface_types_.clear();
4481 }
4482
4483 // This is called for each type.  For a named type, for each of the
4484 // interfaces with hidden methods that it implements, create the
4485 // method table.
4486
4487 int
4488 Build_method_tables::type(Type* type)
4489 {
4490   Named_type* nt = type->named_type();
4491   Struct_type* st = type->struct_type();
4492   if (nt != NULL || st != NULL)
4493     {
4494       Translate_context context(this->gogo_, NULL, NULL, NULL);
4495       for (std::vector<Interface_type*>::const_iterator p =
4496              this->interfaces_.begin();
4497            p != this->interfaces_.end();
4498            ++p)
4499         {
4500           // We ask whether a pointer to the named type implements the
4501           // interface, because a pointer can implement more methods
4502           // than a value.
4503           if (nt != NULL)
4504             {
4505               if ((*p)->implements_interface(Type::make_pointer_type(nt),
4506                                              NULL))
4507                 {
4508                   nt->interface_method_table(*p, false)->get_backend(&context);
4509                   nt->interface_method_table(*p, true)->get_backend(&context);
4510                 }
4511             }
4512           else
4513             {
4514               if ((*p)->implements_interface(Type::make_pointer_type(st),
4515                                              NULL))
4516                 {
4517                   st->interface_method_table(*p, false)->get_backend(&context);
4518                   st->interface_method_table(*p, true)->get_backend(&context);
4519                 }
4520             }
4521         }
4522     }
4523   return TRAVERSE_CONTINUE;
4524 }
4525
4526 // Return an expression which allocates memory to hold values of type TYPE.
4527
4528 Expression*
4529 Gogo::allocate_memory(Type* type, Location location)
4530 {
4531   Expression* td = Expression::make_type_descriptor(type, location);
4532   return Runtime::make_call(Runtime::NEW, location, 1, td);
4533 }
4534
4535 // Traversal class used to check for return statements.
4536
4537 class Check_return_statements_traverse : public Traverse
4538 {
4539  public:
4540   Check_return_statements_traverse()
4541     : Traverse(traverse_functions)
4542   { }
4543
4544   int
4545   function(Named_object*);
4546 };
4547
4548 // Check that a function has a return statement if it needs one.
4549
4550 int
4551 Check_return_statements_traverse::function(Named_object* no)
4552 {
4553   Function* func = no->func_value();
4554   const Function_type* fntype = func->type();
4555   const Typed_identifier_list* results = fntype->results();
4556
4557   // We only need a return statement if there is a return value.
4558   if (results == NULL || results->empty())
4559     return TRAVERSE_CONTINUE;
4560
4561   if (func->block()->may_fall_through())
4562     go_error_at(func->block()->end_location(),
4563                 "missing return at end of function");
4564
4565   return TRAVERSE_CONTINUE;
4566 }
4567
4568 // Check return statements.
4569
4570 void
4571 Gogo::check_return_statements()
4572 {
4573   Check_return_statements_traverse traverse;
4574   this->traverse(&traverse);
4575 }
4576
4577 // Export identifiers as requested.
4578
4579 void
4580 Gogo::do_exports()
4581 {
4582   // For now we always stream to a section.  Later we may want to
4583   // support streaming to a separate file.
4584   Stream_to_section stream(this->backend());
4585
4586   // Write out either the prefix or pkgpath depending on how we were
4587   // invoked.
4588   std::string prefix;
4589   std::string pkgpath;
4590   if (this->pkgpath_from_option_)
4591     pkgpath = this->pkgpath_;
4592   else if (this->prefix_from_option_)
4593     prefix = this->prefix_;
4594   else if (this->is_main_package())
4595     pkgpath = "main";
4596   else
4597     prefix = "go";
4598
4599   Export exp(&stream);
4600   exp.register_builtin_types(this);
4601   exp.export_globals(this->package_name(),
4602                      prefix,
4603                      pkgpath,
4604                      this->packages_,
4605                      this->imports_,
4606                      (this->need_init_fn_ && !this->is_main_package()
4607                       ? this->get_init_fn_name()
4608                       : ""),
4609                      this->imported_init_fns_,
4610                      this->package_->bindings());
4611
4612   if (!this->c_header_.empty() && !saw_errors())
4613     this->write_c_header();
4614 }
4615
4616 // Write the top level named struct types in C format to a C header
4617 // file.  This is used when building the runtime package, to share
4618 // struct definitions between C and Go.
4619
4620 void
4621 Gogo::write_c_header()
4622 {
4623   std::ofstream out;
4624   out.open(this->c_header_.c_str());
4625   if (out.fail())
4626     {
4627       go_error_at(Linemap::unknown_location(),
4628                   "cannot open %s: %m", this->c_header_.c_str());
4629       return;
4630     }
4631
4632   std::list<Named_object*> types;
4633   Bindings* top = this->package_->bindings();
4634   for (Bindings::const_definitions_iterator p = top->begin_definitions();
4635        p != top->end_definitions();
4636        ++p)
4637     {
4638       Named_object* no = *p;
4639
4640       // Skip names that start with underscore followed by something
4641       // other than an uppercase letter, as when compiling the runtime
4642       // package they are mostly types defined by mkrsysinfo.sh based
4643       // on the C system header files.  We don't need to translate
4644       // types to C and back to Go.  But do accept the special cases
4645       // _defer and _panic.
4646       std::string name = Gogo::unpack_hidden_name(no->name());
4647       if (name[0] == '_'
4648           && (name[1] < 'A' || name[1] > 'Z')
4649           && (name != "_defer" && name != "_panic"))
4650         continue;
4651
4652       if (no->is_type() && no->type_value()->struct_type() != NULL)
4653         types.push_back(no);
4654       if (no->is_const() && no->const_value()->type()->integer_type() != NULL)
4655         {
4656           Numeric_constant nc;
4657           unsigned long val;
4658           if (no->const_value()->expr()->numeric_constant_value(&nc)
4659               && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
4660             {
4661               out << "#define " << no->message_name() << ' ' << val
4662                   << std::endl;
4663             }
4664         }
4665     }
4666
4667   std::vector<const Named_object*> written;
4668   int loop = 0;
4669   while (!types.empty())
4670     {
4671       Named_object* no = types.front();
4672       types.pop_front();
4673
4674       std::vector<const Named_object*> requires;
4675       std::vector<const Named_object*> declare;
4676       if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
4677                                                                   &declare))
4678         continue;
4679
4680       bool ok = true;
4681       for (std::vector<const Named_object*>::const_iterator pr
4682              = requires.begin();
4683            pr != requires.end() && ok;
4684            ++pr)
4685         {
4686           for (std::list<Named_object*>::const_iterator pt = types.begin();
4687                pt != types.end() && ok;
4688                ++pt)
4689             if (*pr == *pt)
4690               ok = false;
4691         }
4692       if (!ok)
4693         {
4694           ++loop;
4695           if (loop > 10000)
4696             {
4697               // This should be impossible since the code parsed and
4698               // type checked.
4699               go_unreachable();
4700             }
4701
4702           types.push_back(no);
4703           continue;
4704         }
4705
4706       for (std::vector<const Named_object*>::const_iterator pd
4707              = declare.begin();
4708            pd != declare.end();
4709            ++pd)
4710         {
4711           if (*pd == no)
4712             continue;
4713
4714           std::vector<const Named_object*> drequires;
4715           std::vector<const Named_object*> ddeclare;
4716           if (!(*pd)->type_value()->struct_type()->
4717               can_write_to_c_header(&drequires, &ddeclare))
4718             continue;
4719
4720           bool done = false;
4721           for (std::vector<const Named_object*>::const_iterator pw
4722                  = written.begin();
4723                pw != written.end();
4724                ++pw)
4725             {
4726               if (*pw == *pd)
4727                 {
4728                   done = true;
4729                   break;
4730                 }
4731             }
4732           if (!done)
4733             {
4734               out << std::endl;
4735               out << "struct " << (*pd)->message_name() << ";" << std::endl;
4736               written.push_back(*pd);
4737             }
4738         }
4739
4740       out << std::endl;
4741       out << "struct " << no->message_name() << " {" << std::endl;
4742       no->type_value()->struct_type()->write_to_c_header(out);
4743       out << "};" << std::endl;
4744       written.push_back(no);
4745     }
4746
4747   out.close();
4748   if (out.fail())
4749     go_error_at(Linemap::unknown_location(),
4750                 "error writing to %s: %m", this->c_header_.c_str());
4751 }
4752
4753 // Find the blocks in order to convert named types defined in blocks.
4754
4755 class Convert_named_types : public Traverse
4756 {
4757  public:
4758   Convert_named_types(Gogo* gogo)
4759     : Traverse(traverse_blocks),
4760       gogo_(gogo)
4761   { }
4762
4763  protected:
4764   int
4765   block(Block* block);
4766
4767  private:
4768   Gogo* gogo_;
4769 };
4770
4771 int
4772 Convert_named_types::block(Block* block)
4773 {
4774   this->gogo_->convert_named_types_in_bindings(block->bindings());
4775   return TRAVERSE_CONTINUE;
4776 }
4777
4778 // Convert all named types to the backend representation.  Since named
4779 // types can refer to other types, this needs to be done in the right
4780 // sequence, which is handled by Named_type::convert.  Here we arrange
4781 // to call that for each named type.
4782
4783 void
4784 Gogo::convert_named_types()
4785 {
4786   this->convert_named_types_in_bindings(this->globals_);
4787   for (Packages::iterator p = this->packages_.begin();
4788        p != this->packages_.end();
4789        ++p)
4790     {
4791       Package* package = p->second;
4792       this->convert_named_types_in_bindings(package->bindings());
4793     }
4794
4795   Convert_named_types cnt(this);
4796   this->traverse(&cnt);
4797
4798   // Make all the builtin named types used for type descriptors, and
4799   // then convert them.  They will only be written out if they are
4800   // needed.
4801   Type::make_type_descriptor_type();
4802   Type::make_type_descriptor_ptr_type();
4803   Function_type::make_function_type_descriptor_type();
4804   Pointer_type::make_pointer_type_descriptor_type();
4805   Struct_type::make_struct_type_descriptor_type();
4806   Array_type::make_array_type_descriptor_type();
4807   Array_type::make_slice_type_descriptor_type();
4808   Map_type::make_map_type_descriptor_type();
4809   Channel_type::make_chan_type_descriptor_type();
4810   Interface_type::make_interface_type_descriptor_type();
4811   Expression::make_func_descriptor_type();
4812   Type::convert_builtin_named_types(this);
4813
4814   Runtime::convert_types(this);
4815
4816   this->named_types_are_converted_ = true;
4817 }
4818
4819 // Convert all names types in a set of bindings.
4820
4821 void
4822 Gogo::convert_named_types_in_bindings(Bindings* bindings)
4823 {
4824   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4825        p != bindings->end_definitions();
4826        ++p)
4827     {
4828       if ((*p)->is_type())
4829         (*p)->type_value()->convert(this);
4830     }
4831 }
4832
4833 // Class Function.
4834
4835 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
4836                    Location location)
4837   : type_(type), enclosing_(enclosing), results_(NULL),
4838     closure_var_(NULL), block_(block), location_(location), labels_(),
4839     local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
4840     pragmas_(0), is_sink_(false), results_are_named_(false),
4841     is_unnamed_type_stub_method_(false), calls_recover_(false),
4842     is_recover_thunk_(false), has_recover_thunk_(false),
4843     calls_defer_retaddr_(false), is_type_specific_function_(false),
4844     in_unique_section_(false)
4845 {
4846 }
4847
4848 // Create the named result variables.
4849
4850 void
4851 Function::create_result_variables(Gogo* gogo)
4852 {
4853   const Typed_identifier_list* results = this->type_->results();
4854   if (results == NULL || results->empty())
4855     return;
4856
4857   if (!results->front().name().empty())
4858     this->results_are_named_ = true;
4859
4860   this->results_ = new Results();
4861   this->results_->reserve(results->size());
4862
4863   Block* block = this->block_;
4864   int index = 0;
4865   for (Typed_identifier_list::const_iterator p = results->begin();
4866        p != results->end();
4867        ++p, ++index)
4868     {
4869       std::string name = p->name();
4870       if (name.empty() || Gogo::is_sink_name(name))
4871         {
4872           static int result_counter;
4873           char buf[100];
4874           snprintf(buf, sizeof buf, "$ret%d", result_counter);
4875           ++result_counter;
4876           name = gogo->pack_hidden_name(buf, false);
4877         }
4878       Result_variable* result = new Result_variable(p->type(), this, index,
4879                                                     p->location());
4880       Named_object* no = block->bindings()->add_result_variable(name, result);
4881       if (no->is_result_variable())
4882         this->results_->push_back(no);
4883       else
4884         {
4885           static int dummy_result_count;
4886           char buf[100];
4887           snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
4888           ++dummy_result_count;
4889           name = gogo->pack_hidden_name(buf, false);
4890           no = block->bindings()->add_result_variable(name, result);
4891           go_assert(no->is_result_variable());
4892           this->results_->push_back(no);
4893         }
4894     }
4895 }
4896
4897 // Update the named result variables when cloning a function which
4898 // calls recover.
4899
4900 void
4901 Function::update_result_variables()
4902 {
4903   if (this->results_ == NULL)
4904     return;
4905
4906   for (Results::iterator p = this->results_->begin();
4907        p != this->results_->end();
4908        ++p)
4909     (*p)->result_var_value()->set_function(this);
4910 }
4911
4912 // Whether this method should not be included in the type descriptor.
4913
4914 bool
4915 Function::nointerface() const
4916 {
4917   go_assert(this->is_method());
4918   return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
4919 }
4920
4921 // Record that this method should not be included in the type
4922 // descriptor.
4923
4924 void
4925 Function::set_nointerface()
4926 {
4927   this->pragmas_ |= GOPRAGMA_NOINTERFACE;
4928 }
4929
4930 // Return the closure variable, creating it if necessary.
4931
4932 Named_object*
4933 Function::closure_var()
4934 {
4935   if (this->closure_var_ == NULL)
4936     {
4937       go_assert(this->descriptor_ == NULL);
4938       // We don't know the type of the variable yet.  We add fields as
4939       // we find them.
4940       Location loc = this->type_->location();
4941       Struct_field_list* sfl = new Struct_field_list;
4942       Struct_type* struct_type = Type::make_struct_type(sfl, loc);
4943       struct_type->set_is_struct_incomparable();
4944       Variable* var = new Variable(Type::make_pointer_type(struct_type),
4945                                    NULL, false, false, false, loc);
4946       var->set_is_used();
4947       var->set_is_closure();
4948       this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
4949       // Note that the new variable is not in any binding contour.
4950     }
4951   return this->closure_var_;
4952 }
4953
4954 // Set the type of the closure variable.
4955
4956 void
4957 Function::set_closure_type()
4958 {
4959   if (this->closure_var_ == NULL)
4960     return;
4961   Named_object* closure = this->closure_var_;
4962   Struct_type* st = closure->var_value()->type()->deref()->struct_type();
4963
4964   // The first field of a closure is always a pointer to the function
4965   // code.
4966   Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4967   st->push_field(Struct_field(Typed_identifier(".$f", voidptr_type,
4968                                                this->location_)));
4969
4970   unsigned int index = 1;
4971   for (Closure_fields::const_iterator p = this->closure_fields_.begin();
4972        p != this->closure_fields_.end();
4973        ++p, ++index)
4974     {
4975       Named_object* no = p->first;
4976       char buf[20];
4977       snprintf(buf, sizeof buf, "%u", index);
4978       std::string n = no->name() + buf;
4979       Type* var_type;
4980       if (no->is_variable())
4981         var_type = no->var_value()->type();
4982       else
4983         var_type = no->result_var_value()->type();
4984       Type* field_type = Type::make_pointer_type(var_type);
4985       st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
4986     }
4987 }
4988
4989 // Return whether this function is a method.
4990
4991 bool
4992 Function::is_method() const
4993 {
4994   return this->type_->is_method();
4995 }
4996
4997 // Add a label definition.
4998
4999 Label*
5000 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
5001                                Location location)
5002 {
5003   Label* lnull = NULL;
5004   std::pair<Labels::iterator, bool> ins =
5005     this->labels_.insert(std::make_pair(label_name, lnull));
5006   Label* label;
5007   if (label_name == "_")
5008     {
5009       label = Label::create_dummy_label();
5010       if (ins.second)
5011         ins.first->second = label;
5012     }
5013   else if (ins.second)
5014     {
5015       // This is a new label.
5016       label = new Label(label_name);
5017       ins.first->second = label;
5018     }
5019   else
5020     {
5021       // The label was already in the hash table.
5022       label = ins.first->second;
5023       if (label->is_defined())
5024         {
5025           go_error_at(location, "label %qs already defined",
5026                       Gogo::message_name(label_name).c_str());
5027           go_inform(label->location(), "previous definition of %qs was here",
5028                     Gogo::message_name(label_name).c_str());
5029           return new Label(label_name);
5030         }
5031     }
5032
5033   label->define(location, gogo->bindings_snapshot(location));
5034
5035   // Issue any errors appropriate for any previous goto's to this
5036   // label.
5037   const std::vector<Bindings_snapshot*>& refs(label->refs());
5038   for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
5039        p != refs.end();
5040        ++p)
5041     (*p)->check_goto_to(gogo->current_block());
5042   label->clear_refs();
5043
5044   return label;
5045 }
5046
5047 // Add a reference to a label.
5048
5049 Label*
5050 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5051                               Location location, bool issue_goto_errors)
5052 {
5053   Label* lnull = NULL;
5054   std::pair<Labels::iterator, bool> ins =
5055     this->labels_.insert(std::make_pair(label_name, lnull));
5056   Label* label;
5057   if (!ins.second)
5058     {
5059       // The label was already in the hash table.
5060       label = ins.first->second;
5061     }
5062   else
5063     {
5064       go_assert(ins.first->second == NULL);
5065       label = new Label(label_name);
5066       ins.first->second = label;
5067     }
5068
5069   label->set_is_used();
5070
5071   if (issue_goto_errors)
5072     {
5073       Bindings_snapshot* snapshot = label->snapshot();
5074       if (snapshot != NULL)
5075         snapshot->check_goto_from(gogo->current_block(), location);
5076       else
5077         label->add_snapshot_ref(gogo->bindings_snapshot(location));
5078     }
5079
5080   return label;
5081 }
5082
5083 // Warn about labels that are defined but not used.
5084
5085 void
5086 Function::check_labels() const
5087 {
5088   for (Labels::const_iterator p = this->labels_.begin();
5089        p != this->labels_.end();
5090        p++)
5091     {
5092       Label* label = p->second;
5093       if (!label->is_used())
5094         go_error_at(label->location(), "label %qs defined and not used",
5095                     Gogo::message_name(label->name()).c_str());
5096     }
5097 }
5098
5099 // Swap one function with another.  This is used when building the
5100 // thunk we use to call a function which calls recover.  It may not
5101 // work for any other case.
5102
5103 void
5104 Function::swap_for_recover(Function *x)
5105 {
5106   go_assert(this->enclosing_ == x->enclosing_);
5107   std::swap(this->results_, x->results_);
5108   std::swap(this->closure_var_, x->closure_var_);
5109   std::swap(this->block_, x->block_);
5110   go_assert(this->location_ == x->location_);
5111   go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5112   go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5113 }
5114
5115 // Traverse the tree.
5116
5117 int
5118 Function::traverse(Traverse* traverse)
5119 {
5120   unsigned int traverse_mask = traverse->traverse_mask();
5121
5122   if ((traverse_mask
5123        & (Traverse::traverse_types | Traverse::traverse_expressions))
5124       != 0)
5125     {
5126       if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5127         return TRAVERSE_EXIT;
5128     }
5129
5130   // FIXME: We should check traverse_functions here if nested
5131   // functions are stored in block bindings.
5132   if (this->block_ != NULL
5133       && (traverse_mask
5134           & (Traverse::traverse_variables
5135              | Traverse::traverse_constants
5136              | Traverse::traverse_blocks
5137              | Traverse::traverse_statements
5138              | Traverse::traverse_expressions
5139              | Traverse::traverse_types)) != 0)
5140     {
5141       if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5142         return TRAVERSE_EXIT;
5143     }
5144
5145   return TRAVERSE_CONTINUE;
5146 }
5147
5148 // Work out types for unspecified variables and constants.
5149
5150 void
5151 Function::determine_types()
5152 {
5153   if (this->block_ != NULL)
5154     this->block_->determine_types();
5155 }
5156
5157 // Return the function descriptor, the value you get when you refer to
5158 // the function in Go code without calling it.
5159
5160 Expression*
5161 Function::descriptor(Gogo*, Named_object* no)
5162 {
5163   go_assert(!this->is_method());
5164   go_assert(this->closure_var_ == NULL);
5165   if (this->descriptor_ == NULL)
5166     this->descriptor_ = Expression::make_func_descriptor(no);
5167   return this->descriptor_;
5168 }
5169
5170 // Get a pointer to the variable representing the defer stack for this
5171 // function, making it if necessary.  The value of the variable is set
5172 // by the runtime routines to true if the function is returning,
5173 // rather than panicing through.  A pointer to this variable is used
5174 // as a marker for the functions on the defer stack associated with
5175 // this function.  A function-specific variable permits inlining a
5176 // function which uses defer.
5177
5178 Expression*
5179 Function::defer_stack(Location location)
5180 {
5181   if (this->defer_stack_ == NULL)
5182     {
5183       Type* t = Type::lookup_bool_type();
5184       Expression* n = Expression::make_boolean(false, location);
5185       this->defer_stack_ = Statement::make_temporary(t, n, location);
5186       this->defer_stack_->set_is_address_taken();
5187     }
5188   Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5189                                                          location);
5190   return Expression::make_unary(OPERATOR_AND, ref, location);
5191 }
5192
5193 // Export the function.
5194
5195 void
5196 Function::export_func(Export* exp, const std::string& name) const
5197 {
5198   Function::export_func_with_type(exp, name, this->type_);
5199 }
5200
5201 // Export a function with a type.
5202
5203 void
5204 Function::export_func_with_type(Export* exp, const std::string& name,
5205                                 const Function_type* fntype)
5206 {
5207   exp->write_c_string("func ");
5208
5209   if (fntype->is_method())
5210     {
5211       exp->write_c_string("(");
5212       const Typed_identifier* receiver = fntype->receiver();
5213       exp->write_name(receiver->name());
5214       exp->write_escape(receiver->note());
5215       exp->write_c_string(" ");
5216       exp->write_type(receiver->type());
5217       exp->write_c_string(") ");
5218     }
5219
5220   exp->write_string(name);
5221
5222   exp->write_c_string(" (");
5223   const Typed_identifier_list* parameters = fntype->parameters();
5224   if (parameters != NULL)
5225     {
5226       size_t i = 0;
5227       bool is_varargs = fntype->is_varargs();
5228       bool first = true;
5229       for (Typed_identifier_list::const_iterator p = parameters->begin();
5230            p != parameters->end();
5231            ++p, ++i)
5232         {
5233           if (first)
5234             first = false;
5235           else
5236             exp->write_c_string(", ");
5237           exp->write_name(p->name());
5238           exp->write_escape(p->note());
5239           exp->write_c_string(" ");
5240           if (!is_varargs || p + 1 != parameters->end())
5241             exp->write_type(p->type());
5242           else
5243             {
5244               exp->write_c_string("...");
5245               exp->write_type(p->type()->array_type()->element_type());
5246             }
5247         }
5248     }
5249   exp->write_c_string(")");
5250
5251   const Typed_identifier_list* results = fntype->results();
5252   if (results != NULL)
5253     {
5254       if (results->size() == 1 && results->begin()->name().empty())
5255         {
5256           exp->write_c_string(" ");
5257           exp->write_type(results->begin()->type());
5258         }
5259       else
5260         {
5261           exp->write_c_string(" (");
5262           bool first = true;
5263           for (Typed_identifier_list::const_iterator p = results->begin();
5264                p != results->end();
5265                ++p)
5266             {
5267               if (first)
5268                 first = false;
5269               else
5270                 exp->write_c_string(", ");
5271               exp->write_name(p->name());
5272               exp->write_escape(p->note());
5273               exp->write_c_string(" ");
5274               exp->write_type(p->type());
5275             }
5276           exp->write_c_string(")");
5277         }
5278     }
5279   exp->write_c_string(";\n");
5280 }
5281
5282 // Import a function.
5283
5284 void
5285 Function::import_func(Import* imp, std::string* pname,
5286                       Typed_identifier** preceiver,
5287                       Typed_identifier_list** pparameters,
5288                       Typed_identifier_list** presults,
5289                       bool* is_varargs)
5290 {
5291   imp->require_c_string("func ");
5292
5293   *preceiver = NULL;
5294   if (imp->peek_char() == '(')
5295     {
5296       imp->require_c_string("(");
5297       std::string name = imp->read_name();
5298       std::string escape_note = imp->read_escape();
5299       imp->require_c_string(" ");
5300       Type* rtype = imp->read_type();
5301       *preceiver = new Typed_identifier(name, rtype, imp->location());
5302       (*preceiver)->set_note(escape_note);
5303       imp->require_c_string(") ");
5304     }
5305
5306   *pname = imp->read_identifier();
5307
5308   Typed_identifier_list* parameters;
5309   *is_varargs = false;
5310   imp->require_c_string(" (");
5311   if (imp->peek_char() == ')')
5312     parameters = NULL;
5313   else
5314     {
5315       parameters = new Typed_identifier_list();
5316       while (true)
5317         {
5318           std::string name = imp->read_name();
5319           std::string escape_note = imp->read_escape();
5320           imp->require_c_string(" ");
5321
5322           if (imp->match_c_string("..."))
5323             {
5324               imp->advance(3);
5325               *is_varargs = true;
5326             }
5327
5328           Type* ptype = imp->read_type();
5329           if (*is_varargs)
5330             ptype = Type::make_array_type(ptype, NULL);
5331           Typed_identifier t = Typed_identifier(name, ptype, imp->location());
5332           t.set_note(escape_note);
5333           parameters->push_back(t);
5334           if (imp->peek_char() != ',')
5335             break;
5336           go_assert(!*is_varargs);
5337           imp->require_c_string(", ");
5338         }
5339     }
5340   imp->require_c_string(")");
5341   *pparameters = parameters;
5342
5343   Typed_identifier_list* results;
5344   if (imp->peek_char() != ' ')
5345     results = NULL;
5346   else
5347     {
5348       results = new Typed_identifier_list();
5349       imp->require_c_string(" ");
5350       if (imp->peek_char() != '(')
5351         {
5352           Type* rtype = imp->read_type();
5353           results->push_back(Typed_identifier("", rtype, imp->location()));
5354         }
5355       else
5356         {
5357           imp->require_c_string("(");
5358           while (true)
5359             {
5360               std::string name = imp->read_name();
5361               std::string note = imp->read_escape();
5362               imp->require_c_string(" ");
5363               Type* rtype = imp->read_type();
5364               Typed_identifier t = Typed_identifier(name, rtype,
5365                                                     imp->location());
5366               t.set_note(note);
5367               results->push_back(t);
5368               if (imp->peek_char() != ',')
5369                 break;
5370               imp->require_c_string(", ");
5371             }
5372           imp->require_c_string(")");
5373         }
5374     }
5375   imp->require_c_string(";\n");
5376   *presults = results;
5377 }
5378
5379 // Get the backend representation.
5380
5381 Bfunction*
5382 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
5383 {
5384   if (this->fndecl_ == NULL)
5385     {
5386       std::string asm_name;
5387       bool is_visible = false;
5388       if (no->package() != NULL)
5389         ;
5390       else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
5391         ;
5392       else if (Gogo::unpack_hidden_name(no->name()) == "init"
5393                && !this->type_->is_method())
5394         ;
5395       else if (no->name() == gogo->get_init_fn_name())
5396         {
5397           is_visible = true;
5398           asm_name = no->name();
5399         }
5400       else if (Gogo::unpack_hidden_name(no->name()) == "main"
5401                && gogo->is_main_package())
5402         is_visible = true;
5403       // Methods have to be public even if they are hidden because
5404       // they can be pulled into type descriptors when using
5405       // anonymous fields.
5406       else if (!Gogo::is_hidden_name(no->name())
5407                || this->type_->is_method())
5408         {
5409           if (!this->is_unnamed_type_stub_method_)
5410             is_visible = true;
5411           std::string pkgpath = gogo->pkgpath_symbol();
5412           if (this->type_->is_method()
5413               && Gogo::is_hidden_name(no->name())
5414               && Gogo::hidden_name_pkgpath(no->name()) != gogo->pkgpath())
5415             {
5416               // This is a method we created for an unexported
5417               // method of an imported embedded type.  We need to
5418               // use the pkgpath of the imported package to avoid
5419               // a possible name collision.  See bug478 for a test
5420               // case.
5421               pkgpath = Gogo::hidden_name_pkgpath(no->name());
5422               pkgpath = Gogo::pkgpath_for_symbol(pkgpath);
5423             }
5424
5425           asm_name = pkgpath;
5426           asm_name.append(1, '.');
5427           asm_name.append(Gogo::unpack_hidden_name(no->name()));
5428           if (this->type_->is_method())
5429             {
5430               asm_name.append(1, '.');
5431               Type* rtype = this->type_->receiver()->type();
5432               asm_name.append(rtype->mangled_name(gogo));
5433             }
5434         }
5435
5436       if (!this->asm_name_.empty())
5437         {
5438           asm_name = this->asm_name_;
5439           is_visible = true;
5440         }
5441
5442       // If a function calls the predeclared recover function, we
5443       // can't inline it, because recover behaves differently in a
5444       // function passed directly to defer.  If this is a recover
5445       // thunk that we built to test whether a function can be
5446       // recovered, we can't inline it, because that will mess up
5447       // our return address comparison.
5448       bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
5449
5450       // If a function calls __go_set_defer_retaddr, then mark it as
5451       // uninlinable.  This prevents the GCC backend from splitting
5452       // the function; splitting the function is a bad idea because we
5453       // want the return address label to be in the same function as
5454       // the call.
5455       if (this->calls_defer_retaddr_)
5456         is_inlinable = false;
5457
5458       // Check the //go:noinline compiler directive.
5459       if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
5460         is_inlinable = false;
5461
5462       // If this is a thunk created to call a function which calls
5463       // the predeclared recover function, we need to disable
5464       // stack splitting for the thunk.
5465       bool disable_split_stack = this->is_recover_thunk_;
5466
5467       // Check the //go:nosplit compiler directive.
5468       if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
5469         disable_split_stack = true;
5470
5471       // Encode name if asm_name not already set at this point
5472       if (asm_name.empty() && go_id_needs_encoding(no->get_id(gogo)))
5473         asm_name = go_encode_id(no->get_id(gogo));
5474
5475       // This should go into a unique section if that has been
5476       // requested elsewhere, or if this is a nointerface function.
5477       // We want to put a nointerface function into a unique section
5478       // because there is a good chance that the linker garbage
5479       // collection can discard it.
5480       bool in_unique_section = (this->in_unique_section_
5481                                 || (this->is_method() && this->nointerface()));
5482
5483       Btype* functype = this->type_->get_backend_fntype(gogo);
5484       this->fndecl_ =
5485           gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5486                                     is_visible, false, is_inlinable,
5487                                     disable_split_stack, in_unique_section,
5488                                     this->location());
5489     }
5490   return this->fndecl_;
5491 }
5492
5493 // Get the backend representation.
5494
5495 Bfunction*
5496 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
5497 {
5498   if (this->fndecl_ == NULL)
5499     {
5500       // Let Go code use an asm declaration to pick up a builtin
5501       // function.
5502       if (!this->asm_name_.empty())
5503         {
5504           Bfunction* builtin_decl =
5505             gogo->backend()->lookup_builtin(this->asm_name_);
5506           if (builtin_decl != NULL)
5507             {
5508               this->fndecl_ = builtin_decl;
5509               return this->fndecl_;
5510             }
5511         }
5512
5513       std::string asm_name;
5514       if (this->asm_name_.empty())
5515         {
5516           asm_name = (no->package() == NULL
5517                                   ? gogo->pkgpath_symbol()
5518                                   : no->package()->pkgpath_symbol());
5519           asm_name.append(1, '.');
5520           asm_name.append(Gogo::unpack_hidden_name(no->name()));
5521           if (this->fntype_->is_method())
5522             {
5523               asm_name.append(1, '.');
5524               Type* rtype = this->fntype_->receiver()->type();
5525               asm_name.append(rtype->mangled_name(gogo));
5526             }
5527         }
5528       else if (go_id_needs_encoding(no->get_id(gogo)))
5529         asm_name = go_encode_id(no->get_id(gogo));
5530
5531       Btype* functype = this->fntype_->get_backend_fntype(gogo);
5532       this->fndecl_ =
5533           gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5534                                     true, true, true, false, false,
5535                                     this->location());
5536     }
5537
5538   return this->fndecl_;
5539 }
5540
5541 // Build the descriptor for a function declaration.  This won't
5542 // necessarily happen if the package has just a declaration for the
5543 // function and no other reference to it, but we may still need the
5544 // descriptor for references from other packages.
5545 void
5546 Function_declaration::build_backend_descriptor(Gogo* gogo)
5547 {
5548   if (this->descriptor_ != NULL)
5549     {
5550       Translate_context context(gogo, NULL, NULL, NULL);
5551       this->descriptor_->get_backend(&context);
5552     }
5553 }
5554
5555 // Check that the types used in this declaration's signature are defined.
5556 // Reports errors for any undefined type.
5557
5558 void
5559 Function_declaration::check_types() const
5560 {
5561   // Calling Type::base will give errors for any undefined types.
5562   Function_type* fntype = this->type();
5563   if (fntype->receiver() != NULL)
5564     fntype->receiver()->type()->base();
5565   if (fntype->parameters() != NULL)
5566     {
5567       const Typed_identifier_list* params = fntype->parameters();
5568       for (Typed_identifier_list::const_iterator p = params->begin();
5569            p != params->end();
5570            ++p)
5571         p->type()->base();
5572     }
5573 }
5574
5575 // Return the function's decl after it has been built.
5576
5577 Bfunction*
5578 Function::get_decl() const
5579 {
5580   go_assert(this->fndecl_ != NULL);
5581   return this->fndecl_;
5582 }
5583
5584 // Build the backend representation for the function code.
5585
5586 void
5587 Function::build(Gogo* gogo, Named_object* named_function)
5588 {
5589   Translate_context context(gogo, named_function, NULL, NULL);
5590
5591   // A list of parameter variables for this function.
5592   std::vector<Bvariable*> param_vars;
5593
5594   // Variables that need to be declared for this function and their
5595   // initial values.
5596   std::vector<Bvariable*> vars;
5597   std::vector<Bexpression*> var_inits;
5598   for (Bindings::const_definitions_iterator p =
5599          this->block_->bindings()->begin_definitions();
5600        p != this->block_->bindings()->end_definitions();
5601        ++p)
5602     {
5603       Location loc = (*p)->location();
5604       if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
5605         {
5606           Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5607           Bvariable* parm_bvar = bvar;
5608
5609           // We always pass the receiver to a method as a pointer.  If
5610           // the receiver is declared as a non-pointer type, then we
5611           // copy the value into a local variable.
5612           if ((*p)->var_value()->is_receiver()
5613               && (*p)->var_value()->type()->points_to() == NULL)
5614             {
5615               std::string name = (*p)->name() + ".pointer";
5616               Type* var_type = (*p)->var_value()->type();
5617               Variable* parm_var =
5618                   new Variable(Type::make_pointer_type(var_type), NULL, false,
5619                                true, false, loc);
5620               Named_object* parm_no =
5621                   Named_object::make_variable(name, NULL, parm_var);
5622               parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5623
5624               vars.push_back(bvar);
5625               Expression* parm_ref =
5626                   Expression::make_var_reference(parm_no, loc);
5627               parm_ref = Expression::make_unary(OPERATOR_MULT, parm_ref, loc);
5628               if ((*p)->var_value()->is_in_heap())
5629                 parm_ref = Expression::make_heap_expression(parm_ref, loc);
5630               var_inits.push_back(parm_ref->get_backend(&context));
5631             }
5632           else if ((*p)->var_value()->is_in_heap())
5633             {
5634               // If we take the address of a parameter, then we need
5635               // to copy it into the heap.
5636               std::string parm_name = (*p)->name() + ".param";
5637               Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
5638                                                 false, true, false, loc);
5639               Named_object* parm_no =
5640                   Named_object::make_variable(parm_name, NULL, parm_var);
5641               parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5642
5643               vars.push_back(bvar);
5644               Expression* var_ref =
5645                   Expression::make_var_reference(parm_no, loc);
5646               var_ref = Expression::make_heap_expression(var_ref, loc);
5647               var_inits.push_back(var_ref->get_backend(&context));
5648             }
5649           param_vars.push_back(parm_bvar);
5650         }
5651       else if ((*p)->is_result_variable())
5652         {
5653           Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5654
5655           Type* type = (*p)->result_var_value()->type();
5656           Bexpression* init;
5657           if (!(*p)->result_var_value()->is_in_heap())
5658             {
5659               Btype* btype = type->get_backend(gogo);
5660               init = gogo->backend()->zero_expression(btype);
5661             }
5662           else
5663             init = Expression::make_allocation(type,
5664                                                loc)->get_backend(&context);
5665
5666           vars.push_back(bvar);
5667           var_inits.push_back(init);
5668         }
5669     }
5670   if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
5671     {
5672       go_assert(saw_errors());
5673       return;
5674     }
5675
5676   // If we need a closure variable, make sure to create it.
5677   // It gets installed in the function as a side effect of creation.
5678   if (this->closure_var_ != NULL)
5679     {
5680       go_assert(this->closure_var_->var_value()->is_closure());
5681       this->closure_var_->get_backend_variable(gogo, named_function);
5682     }
5683
5684   if (this->block_ != NULL)
5685     {
5686       // Declare variables if necessary.
5687       Bblock* var_decls = NULL;
5688
5689       Bstatement* defer_init = NULL;
5690       if (!vars.empty() || this->defer_stack_ != NULL)
5691         {
5692           var_decls =
5693               gogo->backend()->block(this->fndecl_, NULL, vars,
5694                                      this->block_->start_location(),
5695                                      this->block_->end_location());
5696
5697           if (this->defer_stack_ != NULL)
5698             {
5699               Translate_context dcontext(gogo, named_function, this->block_,
5700                                          var_decls);
5701               defer_init = this->defer_stack_->get_backend(&dcontext);
5702             }
5703         }
5704
5705       // Build the backend representation for all the statements in the
5706       // function.
5707       Translate_context context(gogo, named_function, NULL, NULL);
5708       Bblock* code_block = this->block_->get_backend(&context);
5709
5710       // Initialize variables if necessary.
5711       std::vector<Bstatement*> init;
5712       go_assert(vars.size() == var_inits.size());
5713       for (size_t i = 0; i < vars.size(); ++i)
5714         {
5715           Bstatement* init_stmt =
5716               gogo->backend()->init_statement(this->fndecl_, vars[i],
5717                                               var_inits[i]);
5718           init.push_back(init_stmt);
5719         }
5720       if (defer_init != NULL)
5721         init.push_back(defer_init);
5722       Bstatement* var_init = gogo->backend()->statement_list(init);
5723
5724       // Initialize all variables before executing this code block.
5725       Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
5726       code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
5727
5728       // If we have a defer stack, initialize it at the start of a
5729       // function.
5730       Bstatement* except = NULL;
5731       Bstatement* fini = NULL;
5732       if (defer_init != NULL)
5733         {
5734           // Clean up the defer stack when we leave the function.
5735           this->build_defer_wrapper(gogo, named_function, &except, &fini);
5736
5737           // Wrap the code for this function in an exception handler to handle
5738           // defer calls.
5739           code_stmt =
5740               gogo->backend()->exception_handler_statement(code_stmt,
5741                                                            except, fini,
5742                                                            this->location_);
5743         }
5744
5745       // Stick the code into the block we built for the receiver, if
5746       // we built one.
5747       if (var_decls != NULL)
5748         {
5749           std::vector<Bstatement*> code_stmt_list(1, code_stmt);
5750           gogo->backend()->block_add_statements(var_decls, code_stmt_list);
5751           code_stmt = gogo->backend()->block_statement(var_decls);
5752         }
5753
5754       if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
5755         {
5756           go_assert(saw_errors());
5757           return;
5758         }
5759     }
5760
5761   // If we created a descriptor for the function, make sure we emit it.
5762   if (this->descriptor_ != NULL)
5763     {
5764       Translate_context context(gogo, NULL, NULL, NULL);
5765       this->descriptor_->get_backend(&context);
5766     }
5767 }
5768
5769 // Build the wrappers around function code needed if the function has
5770 // any defer statements.  This sets *EXCEPT to an exception handler
5771 // and *FINI to a finally handler.
5772
5773 void
5774 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
5775                               Bstatement** except, Bstatement** fini)
5776 {
5777   Location end_loc = this->block_->end_location();
5778
5779   // Add an exception handler.  This is used if a panic occurs.  Its
5780   // purpose is to stop the stack unwinding if a deferred function
5781   // calls recover.  There are more details in
5782   // libgo/runtime/go-unwind.c.
5783
5784   std::vector<Bstatement*> stmts;
5785   Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
5786                                         this->defer_stack(end_loc));
5787   Translate_context context(gogo, named_function, NULL, NULL);
5788   Bexpression* defer = call->get_backend(&context);
5789   stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
5790
5791   Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
5792   if (ret_bstmt != NULL)
5793     stmts.push_back(ret_bstmt);
5794
5795   go_assert(*except == NULL);
5796   *except = gogo->backend()->statement_list(stmts);
5797
5798   call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
5799                             this->defer_stack(end_loc));
5800   defer = call->get_backend(&context);
5801
5802   call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
5803                             this->defer_stack(end_loc));
5804   Bexpression* undefer = call->get_backend(&context);
5805   Bstatement* function_defer =
5806       gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
5807                                                 end_loc);
5808   stmts = std::vector<Bstatement*>(1, function_defer);
5809   if (this->type_->results() != NULL
5810       && !this->type_->results()->empty()
5811       && !this->type_->results()->front().name().empty())
5812     {
5813       // If the result variables are named, and we are returning from
5814       // this function rather than panicing through it, we need to
5815       // return them again, because they might have been changed by a
5816       // defer function.  The runtime routines set the defer_stack
5817       // variable to true if we are returning from this function.
5818
5819       ret_bstmt = this->return_value(gogo, named_function, end_loc);
5820       Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
5821       Bexpression* ret =
5822           gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
5823       Expression* ref =
5824         Expression::make_temporary_reference(this->defer_stack_, end_loc);
5825       Bexpression* bref = ref->get_backend(&context);
5826       ret = gogo->backend()->conditional_expression(this->fndecl_,
5827                                                     NULL, bref, ret, NULL,
5828                                                     end_loc);
5829       stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
5830     }
5831
5832   go_assert(*fini == NULL);
5833   *fini = gogo->backend()->statement_list(stmts);
5834 }
5835
5836 // Return the statement that assigns values to this function's result struct.
5837
5838 Bstatement*
5839 Function::return_value(Gogo* gogo, Named_object* named_function,
5840                        Location location) const
5841 {
5842   const Typed_identifier_list* results = this->type_->results();
5843   if (results == NULL || results->empty())
5844     return NULL;
5845
5846   go_assert(this->results_ != NULL);
5847   if (this->results_->size() != results->size())
5848     {
5849       go_assert(saw_errors());
5850       return gogo->backend()->error_statement();
5851     }
5852
5853   std::vector<Bexpression*> vals(results->size());
5854   for (size_t i = 0; i < vals.size(); ++i)
5855     {
5856       Named_object* no = (*this->results_)[i];
5857       Bvariable* bvar = no->get_backend_variable(gogo, named_function);
5858       Bexpression* val = gogo->backend()->var_expression(bvar, VE_rvalue,
5859                                                          location);
5860       if (no->result_var_value()->is_in_heap())
5861         {
5862           Btype* bt = no->result_var_value()->type()->get_backend(gogo);
5863           val = gogo->backend()->indirect_expression(bt, val, true, location);
5864         }
5865       vals[i] = val;
5866     }
5867   return gogo->backend()->return_statement(this->fndecl_, vals, location);
5868 }
5869
5870 // Class Block.
5871
5872 Block::Block(Block* enclosing, Location location)
5873   : enclosing_(enclosing), statements_(),
5874     bindings_(new Bindings(enclosing == NULL
5875                            ? NULL
5876                            : enclosing->bindings())),
5877     start_location_(location),
5878     end_location_(Linemap::unknown_location())
5879 {
5880 }
5881
5882 // Add a statement to a block.
5883
5884 void
5885 Block::add_statement(Statement* statement)
5886 {
5887   this->statements_.push_back(statement);
5888 }
5889
5890 // Add a statement to the front of a block.  This is slow but is only
5891 // used for reference counts of parameters.
5892
5893 void
5894 Block::add_statement_at_front(Statement* statement)
5895 {
5896   this->statements_.insert(this->statements_.begin(), statement);
5897 }
5898
5899 // Replace a statement in a block.
5900
5901 void
5902 Block::replace_statement(size_t index, Statement* s)
5903 {
5904   go_assert(index < this->statements_.size());
5905   this->statements_[index] = s;
5906 }
5907
5908 // Add a statement before another statement.
5909
5910 void
5911 Block::insert_statement_before(size_t index, Statement* s)
5912 {
5913   go_assert(index < this->statements_.size());
5914   this->statements_.insert(this->statements_.begin() + index, s);
5915 }
5916
5917 // Add a statement after another statement.
5918
5919 void
5920 Block::insert_statement_after(size_t index, Statement* s)
5921 {
5922   go_assert(index < this->statements_.size());
5923   this->statements_.insert(this->statements_.begin() + index + 1, s);
5924 }
5925
5926 // Traverse the tree.
5927
5928 int
5929 Block::traverse(Traverse* traverse)
5930 {
5931   unsigned int traverse_mask = traverse->traverse_mask();
5932
5933   if ((traverse_mask & Traverse::traverse_blocks) != 0)
5934     {
5935       int t = traverse->block(this);
5936       if (t == TRAVERSE_EXIT)
5937         return TRAVERSE_EXIT;
5938       else if (t == TRAVERSE_SKIP_COMPONENTS)
5939         return TRAVERSE_CONTINUE;
5940     }
5941
5942   if ((traverse_mask
5943        & (Traverse::traverse_variables
5944           | Traverse::traverse_constants
5945           | Traverse::traverse_expressions
5946           | Traverse::traverse_types)) != 0)
5947     {
5948       const unsigned int e_or_t = (Traverse::traverse_expressions
5949                                    | Traverse::traverse_types);
5950       const unsigned int e_or_t_or_s = (e_or_t
5951                                         | Traverse::traverse_statements);
5952       for (Bindings::const_definitions_iterator pb =
5953              this->bindings_->begin_definitions();
5954            pb != this->bindings_->end_definitions();
5955            ++pb)
5956         {
5957           int t = TRAVERSE_CONTINUE;
5958           switch ((*pb)->classification())
5959             {
5960             case Named_object::NAMED_OBJECT_CONST:
5961               if ((traverse_mask & Traverse::traverse_constants) != 0)
5962                 t = traverse->constant(*pb, false);
5963               if (t == TRAVERSE_CONTINUE
5964                   && (traverse_mask & e_or_t) != 0)
5965                 {
5966                   Type* tc = (*pb)->const_value()->type();
5967                   if (tc != NULL
5968                       && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5969                     return TRAVERSE_EXIT;
5970                   t = (*pb)->const_value()->traverse_expression(traverse);
5971                 }
5972               break;
5973
5974             case Named_object::NAMED_OBJECT_VAR:
5975             case Named_object::NAMED_OBJECT_RESULT_VAR:
5976               if ((traverse_mask & Traverse::traverse_variables) != 0)
5977                 t = traverse->variable(*pb);
5978               if (t == TRAVERSE_CONTINUE
5979                   && (traverse_mask & e_or_t) != 0)
5980                 {
5981                   if ((*pb)->is_result_variable()
5982                       || (*pb)->var_value()->has_type())
5983                     {
5984                       Type* tv = ((*pb)->is_variable()
5985                                   ? (*pb)->var_value()->type()
5986                                   : (*pb)->result_var_value()->type());
5987                       if (tv != NULL
5988                           && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5989                         return TRAVERSE_EXIT;
5990                     }
5991                 }
5992               if (t == TRAVERSE_CONTINUE
5993                   && (traverse_mask & e_or_t_or_s) != 0
5994                   && (*pb)->is_variable())
5995                 t = (*pb)->var_value()->traverse_expression(traverse,
5996                                                             traverse_mask);
5997               break;
5998
5999             case Named_object::NAMED_OBJECT_FUNC:
6000             case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
6001               go_unreachable();
6002
6003             case Named_object::NAMED_OBJECT_TYPE:
6004               if ((traverse_mask & e_or_t) != 0)
6005                 t = Type::traverse((*pb)->type_value(), traverse);
6006               break;
6007
6008             case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
6009             case Named_object::NAMED_OBJECT_UNKNOWN:
6010             case Named_object::NAMED_OBJECT_ERRONEOUS:
6011               break;
6012
6013             case Named_object::NAMED_OBJECT_PACKAGE:
6014             case Named_object::NAMED_OBJECT_SINK:
6015               go_unreachable();
6016
6017             default:
6018               go_unreachable();
6019             }
6020
6021           if (t == TRAVERSE_EXIT)
6022             return TRAVERSE_EXIT;
6023         }
6024     }
6025
6026   // No point in checking traverse_mask here--if we got here we always
6027   // want to walk the statements.  The traversal can insert new
6028   // statements before or after the current statement.  Inserting
6029   // statements before the current statement requires updating I via
6030   // the pointer; those statements will not be traversed.  Any new
6031   // statements inserted after the current statement will be traversed
6032   // in their turn.
6033   for (size_t i = 0; i < this->statements_.size(); ++i)
6034     {
6035       if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
6036         return TRAVERSE_EXIT;
6037     }
6038
6039   return TRAVERSE_CONTINUE;
6040 }
6041
6042 // Work out types for unspecified variables and constants.
6043
6044 void
6045 Block::determine_types()
6046 {
6047   for (Bindings::const_definitions_iterator pb =
6048          this->bindings_->begin_definitions();
6049        pb != this->bindings_->end_definitions();
6050        ++pb)
6051     {
6052       if ((*pb)->is_variable())
6053         (*pb)->var_value()->determine_type();
6054       else if ((*pb)->is_const())
6055         (*pb)->const_value()->determine_type();
6056     }
6057
6058   for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6059        ps != this->statements_.end();
6060        ++ps)
6061     (*ps)->determine_types();
6062 }
6063
6064 // Return true if the statements in this block may fall through.
6065
6066 bool
6067 Block::may_fall_through() const
6068 {
6069   if (this->statements_.empty())
6070     return true;
6071   return this->statements_.back()->may_fall_through();
6072 }
6073
6074 // Convert a block to the backend representation.
6075
6076 Bblock*
6077 Block::get_backend(Translate_context* context)
6078 {
6079   Gogo* gogo = context->gogo();
6080   Named_object* function = context->function();
6081   std::vector<Bvariable*> vars;
6082   vars.reserve(this->bindings_->size_definitions());
6083   for (Bindings::const_definitions_iterator pv =
6084          this->bindings_->begin_definitions();
6085        pv != this->bindings_->end_definitions();
6086        ++pv)
6087     {
6088       if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
6089         vars.push_back((*pv)->get_backend_variable(gogo, function));
6090     }
6091
6092   go_assert(function != NULL);
6093   Bfunction* bfunction =
6094     function->func_value()->get_or_make_decl(gogo, function);
6095   Bblock* ret = context->backend()->block(bfunction, context->bblock(),
6096                                           vars, this->start_location_,
6097                                           this->end_location_);
6098
6099   Translate_context subcontext(gogo, function, this, ret);
6100   std::vector<Bstatement*> bstatements;
6101   bstatements.reserve(this->statements_.size());
6102   for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
6103        p != this->statements_.end();
6104        ++p)
6105     bstatements.push_back((*p)->get_backend(&subcontext));
6106
6107   context->backend()->block_add_statements(ret, bstatements);
6108
6109   return ret;
6110 }
6111
6112 // Class Bindings_snapshot.
6113
6114 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
6115   : block_(b), counts_(), location_(location)
6116 {
6117   while (b != NULL)
6118     {
6119       this->counts_.push_back(b->bindings()->size_definitions());
6120       b = b->enclosing();
6121     }
6122 }
6123
6124 // Report errors appropriate for a goto from B to this.
6125
6126 void
6127 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
6128 {
6129   size_t dummy;
6130   if (!this->check_goto_block(loc, b, this->block_, &dummy))
6131     return;
6132   this->check_goto_defs(loc, this->block_,
6133                         this->block_->bindings()->size_definitions(),
6134                         this->counts_[0]);
6135 }
6136
6137 // Report errors appropriate for a goto from this to B.
6138
6139 void
6140 Bindings_snapshot::check_goto_to(const Block* b)
6141 {
6142   size_t index;
6143   if (!this->check_goto_block(this->location_, this->block_, b, &index))
6144     return;
6145   this->check_goto_defs(this->location_, b, this->counts_[index],
6146                         b->bindings()->size_definitions());
6147 }
6148
6149 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6150 // Return true if all is well, false if we reported an error.  If this
6151 // returns true, it sets *PINDEX to the number of blocks BTO is above
6152 // BFROM.
6153
6154 bool
6155 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
6156                                     const Block* bto, size_t* pindex)
6157 {
6158   // It is an error if BTO is not either BFROM or above BFROM.
6159   size_t index = 0;
6160   for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
6161     {
6162       if (pb == NULL)
6163         {
6164           go_error_at(loc, "goto jumps into block");
6165           go_inform(bto->start_location(), "goto target block starts here");
6166           return false;
6167         }
6168     }
6169   *pindex = index;
6170   return true;
6171 }
6172
6173 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6174 // CFROM is the number of names defined at the point of the goto and
6175 // CTO is the number of names defined at the point of the label.
6176
6177 void
6178 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
6179                                    size_t cfrom, size_t cto)
6180 {
6181   if (cfrom < cto)
6182     {
6183       Bindings::const_definitions_iterator p =
6184         block->bindings()->begin_definitions();
6185       for (size_t i = 0; i < cfrom; ++i)
6186         {
6187           go_assert(p != block->bindings()->end_definitions());
6188           ++p;
6189         }
6190       go_assert(p != block->bindings()->end_definitions());
6191
6192       std::string n = (*p)->message_name();
6193       go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
6194       go_inform((*p)->location(), "%qs defined here", n.c_str());
6195     }
6196 }
6197
6198 // Class Function_declaration.
6199
6200 // Return the function descriptor.
6201
6202 Expression*
6203 Function_declaration::descriptor(Gogo*, Named_object* no)
6204 {
6205   go_assert(!this->fntype_->is_method());
6206   if (this->descriptor_ == NULL)
6207     this->descriptor_ = Expression::make_func_descriptor(no);
6208   return this->descriptor_;
6209 }
6210
6211 // Class Variable.
6212
6213 Variable::Variable(Type* type, Expression* init, bool is_global,
6214                    bool is_parameter, bool is_receiver,
6215                    Location location)
6216   : type_(type), init_(init), preinit_(NULL), location_(location),
6217     backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
6218     is_closure_(false), is_receiver_(is_receiver),
6219     is_varargs_parameter_(false), is_used_(false),
6220     is_address_taken_(false), is_non_escaping_address_taken_(false),
6221     seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6222     type_from_init_tuple_(false), type_from_range_index_(false),
6223     type_from_range_value_(false), type_from_chan_element_(false),
6224     is_type_switch_var_(false), determined_type_(false),
6225     in_unique_section_(false), escapes_(true)
6226 {
6227   go_assert(type != NULL || init != NULL);
6228   go_assert(!is_parameter || init == NULL);
6229 }
6230
6231 // Traverse the initializer expression.
6232
6233 int
6234 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
6235 {
6236   if (this->preinit_ != NULL)
6237     {
6238       if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
6239         return TRAVERSE_EXIT;
6240     }
6241   if (this->init_ != NULL
6242       && ((traverse_mask
6243            & (Traverse::traverse_expressions | Traverse::traverse_types))
6244           != 0))
6245     {
6246       if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
6247         return TRAVERSE_EXIT;
6248     }
6249   return TRAVERSE_CONTINUE;
6250 }
6251
6252 // Lower the initialization expression after parsing is complete.
6253
6254 void
6255 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
6256                                 Statement_inserter* inserter)
6257 {
6258   Named_object* dep = gogo->var_depends_on(this);
6259   if (dep != NULL && dep->is_variable())
6260     dep->var_value()->lower_init_expression(gogo, function, inserter);
6261
6262   if (this->init_ != NULL && !this->init_is_lowered_)
6263     {
6264       if (this->seen_)
6265         {
6266           // We will give an error elsewhere, this is just to prevent
6267           // an infinite loop.
6268           return;
6269         }
6270       this->seen_ = true;
6271
6272       Statement_inserter global_inserter;
6273       if (this->is_global_)
6274         {
6275           global_inserter = Statement_inserter(gogo, this);
6276           inserter = &global_inserter;
6277         }
6278
6279       gogo->lower_expression(function, inserter, &this->init_);
6280
6281       this->seen_ = false;
6282
6283       this->init_is_lowered_ = true;
6284     }
6285 }
6286
6287 // Flatten the initialization expression after ordering evaluations.
6288
6289 void
6290 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
6291                                   Statement_inserter* inserter)
6292 {
6293   Named_object* dep = gogo->var_depends_on(this);
6294   if (dep != NULL && dep->is_variable())
6295     dep->var_value()->flatten_init_expression(gogo, function, inserter);
6296
6297   if (this->init_ != NULL && !this->init_is_flattened_)
6298     {
6299       if (this->seen_)
6300         {
6301           // We will give an error elsewhere, this is just to prevent
6302           // an infinite loop.
6303           return;
6304         }
6305       this->seen_ = true;
6306
6307       Statement_inserter global_inserter;
6308       if (this->is_global_)
6309         {
6310           global_inserter = Statement_inserter(gogo, this);
6311           inserter = &global_inserter;
6312         }
6313
6314       gogo->flatten_expression(function, inserter, &this->init_);
6315
6316       // If an interface conversion is needed, we need a temporary
6317       // variable.
6318       if (this->type_ != NULL
6319           && !Type::are_identical(this->type_, this->init_->type(), false,
6320                                   NULL)
6321           && this->init_->type()->interface_type() != NULL
6322           && !this->init_->is_variable())
6323         {
6324           Temporary_statement* temp =
6325             Statement::make_temporary(NULL, this->init_, this->location_);
6326           inserter->insert(temp);
6327           this->init_ = Expression::make_temporary_reference(temp,
6328                                                              this->location_);
6329         }
6330
6331       this->seen_ = false;
6332       this->init_is_flattened_ = true;
6333     }
6334 }
6335
6336 // Get the preinit block.
6337
6338 Block*
6339 Variable::preinit_block(Gogo* gogo)
6340 {
6341   go_assert(this->is_global_);
6342   if (this->preinit_ == NULL)
6343     this->preinit_ = new Block(NULL, this->location());
6344
6345   // If a global variable has a preinitialization statement, then we
6346   // need to have an initialization function.
6347   gogo->set_need_init_fn();
6348
6349   return this->preinit_;
6350 }
6351
6352 // Add a statement to be run before the initialization expression.
6353
6354 void
6355 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
6356 {
6357   Block* b = this->preinit_block(gogo);
6358   b->add_statement(s);
6359   b->set_end_location(s->location());
6360 }
6361
6362 // Whether this variable has a type.
6363
6364 bool
6365 Variable::has_type() const
6366 {
6367   if (this->type_ == NULL)
6368     return false;
6369
6370   // A variable created in a type switch case nil does not actually
6371   // have a type yet.  It will be changed to use the initializer's
6372   // type in determine_type.
6373   if (this->is_type_switch_var_
6374       && this->type_->is_nil_constant_as_type())
6375     return false;
6376
6377   return true;
6378 }
6379
6380 // In an assignment which sets a variable to a tuple of EXPR, return
6381 // the type of the first element of the tuple.
6382
6383 Type*
6384 Variable::type_from_tuple(Expression* expr, bool report_error) const
6385 {
6386   if (expr->map_index_expression() != NULL)
6387     {
6388       Map_type* mt = expr->map_index_expression()->get_map_type();
6389       if (mt == NULL)
6390         return Type::make_error_type();
6391       return mt->val_type();
6392     }
6393   else if (expr->receive_expression() != NULL)
6394     {
6395       Expression* channel = expr->receive_expression()->channel();
6396       Type* channel_type = channel->type();
6397       if (channel_type->channel_type() == NULL)
6398         return Type::make_error_type();
6399       return channel_type->channel_type()->element_type();
6400     }
6401   else
6402     {
6403       if (report_error)
6404         go_error_at(this->location(), "invalid tuple definition");
6405       return Type::make_error_type();
6406     }
6407 }
6408
6409 // Given EXPR used in a range clause, return either the index type or
6410 // the value type of the range, depending upon GET_INDEX_TYPE.
6411
6412 Type*
6413 Variable::type_from_range(Expression* expr, bool get_index_type,
6414                           bool report_error) const
6415 {
6416   Type* t = expr->type();
6417   if (t->array_type() != NULL
6418       || (t->points_to() != NULL
6419           && t->points_to()->array_type() != NULL
6420           && !t->points_to()->is_slice_type()))
6421     {
6422       if (get_index_type)
6423         return Type::lookup_integer_type("int");
6424       else
6425         return t->deref()->array_type()->element_type();
6426     }
6427   else if (t->is_string_type())
6428     {
6429       if (get_index_type)
6430         return Type::lookup_integer_type("int");
6431       else
6432         return Type::lookup_integer_type("int32");
6433     }
6434   else if (t->map_type() != NULL)
6435     {
6436       if (get_index_type)
6437         return t->map_type()->key_type();
6438       else
6439         return t->map_type()->val_type();
6440     }
6441   else if (t->channel_type() != NULL)
6442     {
6443       if (get_index_type)
6444         return t->channel_type()->element_type();
6445       else
6446         {
6447           if (report_error)
6448             go_error_at(this->location(),
6449                         ("invalid definition of value variable "
6450                          "for channel range"));
6451           return Type::make_error_type();
6452         }
6453     }
6454   else
6455     {
6456       if (report_error)
6457         go_error_at(this->location(), "invalid type for range clause");
6458       return Type::make_error_type();
6459     }
6460 }
6461
6462 // EXPR should be a channel.  Return the channel's element type.
6463
6464 Type*
6465 Variable::type_from_chan_element(Expression* expr, bool report_error) const
6466 {
6467   Type* t = expr->type();
6468   if (t->channel_type() != NULL)
6469     return t->channel_type()->element_type();
6470   else
6471     {
6472       if (report_error)
6473         go_error_at(this->location(), "expected channel");
6474       return Type::make_error_type();
6475     }
6476 }
6477
6478 // Return the type of the Variable.  This may be called before
6479 // Variable::determine_type is called, which means that we may need to
6480 // get the type from the initializer.  FIXME: If we combine lowering
6481 // with type determination, then this should be unnecessary.
6482
6483 Type*
6484 Variable::type()
6485 {
6486   // A variable in a type switch with a nil case will have the wrong
6487   // type here.  This gets fixed up in determine_type, below.
6488   Type* type = this->type_;
6489   Expression* init = this->init_;
6490   if (this->is_type_switch_var_
6491       && type != NULL
6492       && this->type_->is_nil_constant_as_type())
6493     {
6494       Type_guard_expression* tge = this->init_->type_guard_expression();
6495       go_assert(tge != NULL);
6496       init = tge->expr();
6497       type = NULL;
6498     }
6499
6500   if (this->seen_)
6501     {
6502       if (this->type_ == NULL || !this->type_->is_error_type())
6503         {
6504           go_error_at(this->location_, "variable initializer refers to itself");
6505           this->type_ = Type::make_error_type();
6506         }
6507       return this->type_;
6508     }
6509
6510   this->seen_ = true;
6511
6512   if (type != NULL)
6513     ;
6514   else if (this->type_from_init_tuple_)
6515     type = this->type_from_tuple(init, false);
6516   else if (this->type_from_range_index_ || this->type_from_range_value_)
6517     type = this->type_from_range(init, this->type_from_range_index_, false);
6518   else if (this->type_from_chan_element_)
6519     type = this->type_from_chan_element(init, false);
6520   else
6521     {
6522       go_assert(init != NULL);
6523       type = init->type();
6524       go_assert(type != NULL);
6525
6526       // Variables should not have abstract types.
6527       if (type->is_abstract())
6528         type = type->make_non_abstract_type();
6529
6530       if (type->is_void_type())
6531         type = Type::make_error_type();
6532     }
6533
6534   this->seen_ = false;
6535
6536   return type;
6537 }
6538
6539 // Fetch the type from a const pointer, in which case it should have
6540 // been set already.
6541
6542 Type*
6543 Variable::type() const
6544 {
6545   go_assert(this->type_ != NULL);
6546   return this->type_;
6547 }
6548
6549 // Set the type if necessary.
6550
6551 void
6552 Variable::determine_type()
6553 {
6554   if (this->determined_type_)
6555     return;
6556   this->determined_type_ = true;
6557
6558   if (this->preinit_ != NULL)
6559     this->preinit_->determine_types();
6560
6561   // A variable in a type switch with a nil case will have the wrong
6562   // type here.  It will have an initializer which is a type guard.
6563   // We want to initialize it to the value without the type guard, and
6564   // use the type of that value as well.
6565   if (this->is_type_switch_var_
6566       && this->type_ != NULL
6567       && this->type_->is_nil_constant_as_type())
6568     {
6569       Type_guard_expression* tge = this->init_->type_guard_expression();
6570       go_assert(tge != NULL);
6571       this->type_ = NULL;
6572       this->init_ = tge->expr();
6573     }
6574
6575   if (this->init_ == NULL)
6576     go_assert(this->type_ != NULL && !this->type_->is_abstract());
6577   else if (this->type_from_init_tuple_)
6578     {
6579       Expression *init = this->init_;
6580       init->determine_type_no_context();
6581       this->type_ = this->type_from_tuple(init, true);
6582       this->init_ = NULL;
6583     }
6584   else if (this->type_from_range_index_ || this->type_from_range_value_)
6585     {
6586       Expression* init = this->init_;
6587       init->determine_type_no_context();
6588       this->type_ = this->type_from_range(init, this->type_from_range_index_,
6589                                           true);
6590       this->init_ = NULL;
6591     }
6592   else if (this->type_from_chan_element_)
6593     {
6594       Expression* init = this->init_;
6595       init->determine_type_no_context();
6596       this->type_ = this->type_from_chan_element(init, true);
6597       this->init_ = NULL;
6598     }
6599   else
6600     {
6601       Type_context context(this->type_, false);
6602       this->init_->determine_type(&context);
6603       if (this->type_ == NULL)
6604         {
6605           Type* type = this->init_->type();
6606           go_assert(type != NULL);
6607           if (type->is_abstract())
6608             type = type->make_non_abstract_type();
6609
6610           if (type->is_void_type())
6611             {
6612               go_error_at(this->location_, "variable has no type");
6613               type = Type::make_error_type();
6614             }
6615           else if (type->is_nil_type())
6616             {
6617               go_error_at(this->location_, "variable defined to nil type");
6618               type = Type::make_error_type();
6619             }
6620           else if (type->is_call_multiple_result_type())
6621             {
6622               go_error_at(this->location_,
6623                        "single variable set to multiple-value function call");
6624               type = Type::make_error_type();
6625             }
6626
6627           this->type_ = type;
6628         }
6629     }
6630 }
6631
6632 // Get the initial value of a variable.  This does not
6633 // consider whether the variable is in the heap--it returns the
6634 // initial value as though it were always stored in the stack.
6635
6636 Bexpression*
6637 Variable::get_init(Gogo* gogo, Named_object* function)
6638 {
6639   go_assert(this->preinit_ == NULL);
6640   Location loc = this->location();
6641   if (this->init_ == NULL)
6642     {
6643       go_assert(!this->is_parameter_);
6644       if (this->is_global_ || this->is_in_heap())
6645         return NULL;
6646       Btype* btype = this->type()->get_backend(gogo);
6647       return gogo->backend()->zero_expression(btype);
6648     }
6649   else
6650     {
6651       Translate_context context(gogo, function, NULL, NULL);
6652       Expression* init = Expression::make_cast(this->type(), this->init_, loc);
6653       return init->get_backend(&context);
6654     }
6655 }
6656
6657 // Get the initial value of a variable when a block is required.
6658 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6659
6660 Bstatement*
6661 Variable::get_init_block(Gogo* gogo, Named_object* function,
6662                          Bvariable* var_decl)
6663 {
6664   go_assert(this->preinit_ != NULL);
6665
6666   // We want to add the variable assignment to the end of the preinit
6667   // block.
6668
6669   Translate_context context(gogo, function, NULL, NULL);
6670   Bblock* bblock = this->preinit_->get_backend(&context);
6671   Bfunction* bfunction =
6672       function->func_value()->get_or_make_decl(gogo, function);
6673
6674   // It's possible to have pre-init statements without an initializer
6675   // if the pre-init statements set the variable.
6676   Bstatement* decl_init = NULL;
6677   if (this->init_ != NULL)
6678     {
6679       if (var_decl == NULL)
6680         {
6681           Bexpression* init_bexpr = this->init_->get_backend(&context);
6682           decl_init = gogo->backend()->expression_statement(bfunction,
6683                                                             init_bexpr);
6684         }
6685       else
6686         {
6687           Location loc = this->location();
6688           Expression* val_expr =
6689               Expression::make_cast(this->type(), this->init_, loc);
6690           Bexpression* val = val_expr->get_backend(&context);
6691           Bexpression* var_ref =
6692               gogo->backend()->var_expression(var_decl, VE_lvalue, loc);
6693           decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
6694                                                             val, loc);
6695         }
6696     }
6697   Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
6698   if (decl_init != NULL)
6699     block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
6700   return block_stmt;
6701 }
6702
6703 // Export the variable
6704
6705 void
6706 Variable::export_var(Export* exp, const std::string& name) const
6707 {
6708   go_assert(this->is_global_);
6709   exp->write_c_string("var ");
6710   exp->write_string(name);
6711   exp->write_c_string(" ");
6712   exp->write_type(this->type());
6713   exp->write_c_string(";\n");
6714 }
6715
6716 // Import a variable.
6717
6718 void
6719 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
6720 {
6721   imp->require_c_string("var ");
6722   *pname = imp->read_identifier();
6723   imp->require_c_string(" ");
6724   *ptype = imp->read_type();
6725   imp->require_c_string(";\n");
6726 }
6727
6728 // Convert a variable to the backend representation.
6729
6730 Bvariable*
6731 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
6732                                const Package* package, const std::string& name)
6733 {
6734   if (this->backend_ == NULL)
6735     {
6736       Backend* backend = gogo->backend();
6737       Type* type = this->type_;
6738       if (type->is_error_type()
6739           || (type->is_undefined()
6740               && (!this->is_global_ || package == NULL)))
6741         this->backend_ = backend->error_variable();
6742       else
6743         {
6744           bool is_parameter = this->is_parameter_;
6745           if (this->is_receiver_ && type->points_to() == NULL)
6746             is_parameter = false;
6747           if (this->is_in_heap())
6748             {
6749               is_parameter = false;
6750               type = Type::make_pointer_type(type);
6751             }
6752
6753           const std::string n = Gogo::unpack_hidden_name(name);
6754           Btype* btype = type->get_backend(gogo);
6755
6756           Bvariable* bvar;
6757           if (Map_type::is_zero_value(this))
6758             bvar = Map_type::backend_zero_value(gogo);
6759           else if (this->is_global_)
6760             {
6761               std::string var_name(package != NULL
6762                                    ? package->package_name()
6763                                    : gogo->package_name());
6764               var_name.push_back('.');
6765               var_name.append(n);
6766               std::string asm_name;
6767               if (Gogo::is_hidden_name(name))
6768                 asm_name = var_name;
6769               else
6770                 {
6771                   asm_name = package != NULL
6772                       ? package->pkgpath_symbol()
6773                       : gogo->pkgpath_symbol();
6774                   asm_name.push_back('.');
6775                   asm_name.append(n);
6776                 }
6777               asm_name = go_encode_id(asm_name);
6778
6779               bool is_hidden = Gogo::is_hidden_name(name);
6780               // Hack to export runtime.writeBarrier.  FIXME.
6781               // This is because go:linkname doesn't work on variables.
6782               if (gogo->compiling_runtime()
6783                   && var_name == "runtime.writeBarrier")
6784                 is_hidden = false;
6785
6786               bvar = backend->global_variable(var_name,
6787                                               asm_name,
6788                                               btype,
6789                                               package != NULL,
6790                                               is_hidden,
6791                                               this->in_unique_section_,
6792                                               this->location_);
6793             }
6794           else if (function == NULL)
6795             {
6796               go_assert(saw_errors());
6797               bvar = backend->error_variable();
6798             }
6799           else
6800             {
6801               Bfunction* bfunction = function->func_value()->get_decl();
6802               bool is_address_taken = (this->is_non_escaping_address_taken_
6803                                        && !this->is_in_heap());
6804               if (this->is_closure())
6805                 bvar = backend->static_chain_variable(bfunction, n, btype,
6806                                                       this->location_);
6807               else if (is_parameter)
6808                 bvar = backend->parameter_variable(bfunction, n, btype,
6809                                                    is_address_taken,
6810                                                    this->location_);
6811               else
6812                 bvar = backend->local_variable(bfunction, n, btype,
6813                                                is_address_taken,
6814                                                this->location_);
6815             }
6816           this->backend_ = bvar;
6817         }
6818     }
6819   return this->backend_;
6820 }
6821
6822 // Class Result_variable.
6823
6824 // Convert a result variable to the backend representation.
6825
6826 Bvariable*
6827 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
6828                                       const std::string& name)
6829 {
6830   if (this->backend_ == NULL)
6831     {
6832       Backend* backend = gogo->backend();
6833       Type* type = this->type_;
6834       if (type->is_error())
6835         this->backend_ = backend->error_variable();
6836       else
6837         {
6838           if (this->is_in_heap())
6839             type = Type::make_pointer_type(type);
6840           Btype* btype = type->get_backend(gogo);
6841           Bfunction* bfunction = function->func_value()->get_decl();
6842           std::string n = Gogo::unpack_hidden_name(name);
6843           bool is_address_taken = (this->is_non_escaping_address_taken_
6844                                    && !this->is_in_heap());
6845           this->backend_ = backend->local_variable(bfunction, n, btype,
6846                                                    is_address_taken,
6847                                                    this->location_);
6848         }
6849     }
6850   return this->backend_;
6851 }
6852
6853 // Class Named_constant.
6854
6855 // Traverse the initializer expression.
6856
6857 int
6858 Named_constant::traverse_expression(Traverse* traverse)
6859 {
6860   return Expression::traverse(&this->expr_, traverse);
6861 }
6862
6863 // Determine the type of the constant.
6864
6865 void
6866 Named_constant::determine_type()
6867 {
6868   if (this->type_ != NULL)
6869     {
6870       Type_context context(this->type_, false);
6871       this->expr_->determine_type(&context);
6872     }
6873   else
6874     {
6875       // A constant may have an abstract type.
6876       Type_context context(NULL, true);
6877       this->expr_->determine_type(&context);
6878       this->type_ = this->expr_->type();
6879       go_assert(this->type_ != NULL);
6880     }
6881 }
6882
6883 // Indicate that we found and reported an error for this constant.
6884
6885 void
6886 Named_constant::set_error()
6887 {
6888   this->type_ = Type::make_error_type();
6889   this->expr_ = Expression::make_error(this->location_);
6890 }
6891
6892 // Export a constant.
6893
6894 void
6895 Named_constant::export_const(Export* exp, const std::string& name) const
6896 {
6897   exp->write_c_string("const ");
6898   exp->write_string(name);
6899   exp->write_c_string(" ");
6900   if (!this->type_->is_abstract())
6901     {
6902       exp->write_type(this->type_);
6903       exp->write_c_string(" ");
6904     }
6905   exp->write_c_string("= ");
6906   this->expr()->export_expression(exp);
6907   exp->write_c_string(";\n");
6908 }
6909
6910 // Import a constant.
6911
6912 void
6913 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
6914                              Expression** pexpr)
6915 {
6916   imp->require_c_string("const ");
6917   *pname = imp->read_identifier();
6918   imp->require_c_string(" ");
6919   if (imp->peek_char() == '=')
6920     *ptype = NULL;
6921   else
6922     {
6923       *ptype = imp->read_type();
6924       imp->require_c_string(" ");
6925     }
6926   imp->require_c_string("= ");
6927   *pexpr = Expression::import_expression(imp);
6928   imp->require_c_string(";\n");
6929 }
6930
6931 // Get the backend representation.
6932
6933 Bexpression*
6934 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
6935 {
6936   if (this->bconst_ == NULL)
6937     {
6938       Translate_context subcontext(gogo, NULL, NULL, NULL);
6939       Type* type = this->type();
6940       Location loc = this->location();
6941
6942       Expression* const_ref = Expression::make_const_reference(const_no, loc);
6943       Bexpression* const_decl = const_ref->get_backend(&subcontext);
6944       if (type != NULL && type->is_numeric_type())
6945         {
6946           Btype* btype = type->get_backend(gogo);
6947           std::string name = const_no->get_id(gogo);
6948           const_decl =
6949             gogo->backend()->named_constant_expression(btype, name,
6950                                                        const_decl, loc);
6951         }
6952       this->bconst_ = const_decl;
6953     }
6954   return this->bconst_;
6955 }
6956
6957 // Add a method.
6958
6959 Named_object*
6960 Type_declaration::add_method(const std::string& name, Function* function)
6961 {
6962   Named_object* ret = Named_object::make_function(name, NULL, function);
6963   this->methods_.push_back(ret);
6964   return ret;
6965 }
6966
6967 // Add a method declaration.
6968
6969 Named_object*
6970 Type_declaration::add_method_declaration(const std::string&  name,
6971                                          Package* package,
6972                                          Function_type* type,
6973                                          Location location)
6974 {
6975   Named_object* ret = Named_object::make_function_declaration(name, package,
6976                                                               type, location);
6977   this->methods_.push_back(ret);
6978   return ret;
6979 }
6980
6981 // Return whether any methods are defined.
6982
6983 bool
6984 Type_declaration::has_methods() const
6985 {
6986   return !this->methods_.empty();
6987 }
6988
6989 // Define methods for the real type.
6990
6991 void
6992 Type_declaration::define_methods(Named_type* nt)
6993 {
6994   if (this->methods_.empty())
6995     return;
6996
6997   while (nt->is_alias())
6998     {
6999       Type *t = nt->real_type()->forwarded();
7000       if (t->named_type() != NULL)
7001         nt = t->named_type();
7002       else if (t->forward_declaration_type() != NULL)
7003         {
7004           Named_object* no = t->forward_declaration_type()->named_object();
7005           Type_declaration* td = no->type_declaration_value();
7006           td->methods_.insert(td->methods_.end(), this->methods_.begin(),
7007                               this->methods_.end());
7008           this->methods_.clear();
7009           return;
7010         }
7011       else
7012         {
7013           for (std::vector<Named_object*>::const_iterator p =
7014                  this->methods_.begin();
7015                p != this->methods_.end();
7016                ++p)
7017             go_error_at((*p)->location(),
7018                         ("invalid receiver type "
7019                          "(receiver must be a named type"));
7020           return;
7021         }
7022     }
7023
7024   for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
7025        p != this->methods_.end();
7026        ++p)
7027     {
7028       if (!(*p)->func_value()->is_sink())
7029         nt->add_existing_method(*p);
7030     }
7031 }
7032
7033 // We are using the type.  Return true if we should issue a warning.
7034
7035 bool
7036 Type_declaration::using_type()
7037 {
7038   bool ret = !this->issued_warning_;
7039   this->issued_warning_ = true;
7040   return ret;
7041 }
7042
7043 // Class Unknown_name.
7044
7045 // Set the real named object.
7046
7047 void
7048 Unknown_name::set_real_named_object(Named_object* no)
7049 {
7050   go_assert(this->real_named_object_ == NULL);
7051   go_assert(!no->is_unknown());
7052   this->real_named_object_ = no;
7053 }
7054
7055 // Class Named_object.
7056
7057 Named_object::Named_object(const std::string& name,
7058                            const Package* package,
7059                            Classification classification)
7060   : name_(name), package_(package), classification_(classification),
7061     is_redefinition_(false)
7062 {
7063   if (Gogo::is_sink_name(name))
7064     go_assert(classification == NAMED_OBJECT_SINK);
7065 }
7066
7067 // Make an unknown name.  This is used by the parser.  The name must
7068 // be resolved later.  Unknown names are only added in the current
7069 // package.
7070
7071 Named_object*
7072 Named_object::make_unknown_name(const std::string& name,
7073                                 Location location)
7074 {
7075   Named_object* named_object = new Named_object(name, NULL,
7076                                                 NAMED_OBJECT_UNKNOWN);
7077   Unknown_name* value = new Unknown_name(location);
7078   named_object->u_.unknown_value = value;
7079   return named_object;
7080 }
7081
7082 // Make a constant.
7083
7084 Named_object*
7085 Named_object::make_constant(const Typed_identifier& tid,
7086                             const Package* package, Expression* expr,
7087                             int iota_value)
7088 {
7089   Named_object* named_object = new Named_object(tid.name(), package,
7090                                                 NAMED_OBJECT_CONST);
7091   Named_constant* named_constant = new Named_constant(tid.type(), expr,
7092                                                       iota_value,
7093                                                       tid.location());
7094   named_object->u_.const_value = named_constant;
7095   return named_object;
7096 }
7097
7098 // Make a named type.
7099
7100 Named_object*
7101 Named_object::make_type(const std::string& name, const Package* package,
7102                         Type* type, Location location)
7103 {
7104   Named_object* named_object = new Named_object(name, package,
7105                                                 NAMED_OBJECT_TYPE);
7106   Named_type* named_type = Type::make_named_type(named_object, type, location);
7107   named_object->u_.type_value = named_type;
7108   return named_object;
7109 }
7110
7111 // Make a type declaration.
7112
7113 Named_object*
7114 Named_object::make_type_declaration(const std::string& name,
7115                                     const Package* package,
7116                                     Location location)
7117 {
7118   Named_object* named_object = new Named_object(name, package,
7119                                                 NAMED_OBJECT_TYPE_DECLARATION);
7120   Type_declaration* type_declaration = new Type_declaration(location);
7121   named_object->u_.type_declaration = type_declaration;
7122   return named_object;
7123 }
7124
7125 // Make a variable.
7126
7127 Named_object*
7128 Named_object::make_variable(const std::string& name, const Package* package,
7129                             Variable* variable)
7130 {
7131   Named_object* named_object = new Named_object(name, package,
7132                                                 NAMED_OBJECT_VAR);
7133   named_object->u_.var_value = variable;
7134   return named_object;
7135 }
7136
7137 // Make a result variable.
7138
7139 Named_object*
7140 Named_object::make_result_variable(const std::string& name,
7141                                    Result_variable* result)
7142 {
7143   Named_object* named_object = new Named_object(name, NULL,
7144                                                 NAMED_OBJECT_RESULT_VAR);
7145   named_object->u_.result_var_value = result;
7146   return named_object;
7147 }
7148
7149 // Make a sink.  This is used for the special blank identifier _.
7150
7151 Named_object*
7152 Named_object::make_sink()
7153 {
7154   return new Named_object("_", NULL, NAMED_OBJECT_SINK);
7155 }
7156
7157 // Make a named function.
7158
7159 Named_object*
7160 Named_object::make_function(const std::string& name, const Package* package,
7161                             Function* function)
7162 {
7163   Named_object* named_object = new Named_object(name, package,
7164                                                 NAMED_OBJECT_FUNC);
7165   named_object->u_.func_value = function;
7166   return named_object;
7167 }
7168
7169 // Make a function declaration.
7170
7171 Named_object*
7172 Named_object::make_function_declaration(const std::string& name,
7173                                         const Package* package,
7174                                         Function_type* fntype,
7175                                         Location location)
7176 {
7177   Named_object* named_object = new Named_object(name, package,
7178                                                 NAMED_OBJECT_FUNC_DECLARATION);
7179   Function_declaration *func_decl = new Function_declaration(fntype, location);
7180   named_object->u_.func_declaration_value = func_decl;
7181   return named_object;
7182 }
7183
7184 // Make a package.
7185
7186 Named_object*
7187 Named_object::make_package(const std::string& alias, Package* package)
7188 {
7189   Named_object* named_object = new Named_object(alias, NULL,
7190                                                 NAMED_OBJECT_PACKAGE);
7191   named_object->u_.package_value = package;
7192   return named_object;
7193 }
7194
7195 // Return the name to use in an error message.
7196
7197 std::string
7198 Named_object::message_name() const
7199 {
7200   if (this->package_ == NULL)
7201     return Gogo::message_name(this->name_);
7202   std::string ret;
7203   if (this->package_->has_package_name())
7204     ret = this->package_->package_name();
7205   else
7206     ret = this->package_->pkgpath();
7207   ret = Gogo::message_name(ret);
7208   ret += '.';
7209   ret += Gogo::message_name(this->name_);
7210   return ret;
7211 }
7212
7213 // Set the type when a declaration is defined.
7214
7215 void
7216 Named_object::set_type_value(Named_type* named_type)
7217 {
7218   go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
7219   Type_declaration* td = this->u_.type_declaration;
7220   td->define_methods(named_type);
7221   unsigned int index;
7222   Named_object* in_function = td->in_function(&index);
7223   if (in_function != NULL)
7224     named_type->set_in_function(in_function, index);
7225   delete td;
7226   this->classification_ = NAMED_OBJECT_TYPE;
7227   this->u_.type_value = named_type;
7228 }
7229
7230 // Define a function which was previously declared.
7231
7232 void
7233 Named_object::set_function_value(Function* function)
7234 {
7235   go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
7236   if (this->func_declaration_value()->has_descriptor())
7237     {
7238       Expression* descriptor =
7239         this->func_declaration_value()->descriptor(NULL, NULL);
7240       function->set_descriptor(descriptor);
7241     }
7242   this->classification_ = NAMED_OBJECT_FUNC;
7243   // FIXME: We should free the old value.
7244   this->u_.func_value = function;
7245 }
7246
7247 // Declare an unknown object as a type declaration.
7248
7249 void
7250 Named_object::declare_as_type()
7251 {
7252   go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
7253   Unknown_name* unk = this->u_.unknown_value;
7254   this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
7255   this->u_.type_declaration = new Type_declaration(unk->location());
7256   delete unk;
7257 }
7258
7259 // Return the location of a named object.
7260
7261 Location
7262 Named_object::location() const
7263 {
7264   switch (this->classification_)
7265     {
7266     default:
7267     case NAMED_OBJECT_UNINITIALIZED:
7268       go_unreachable();
7269
7270     case NAMED_OBJECT_ERRONEOUS:
7271       return Linemap::unknown_location();
7272
7273     case NAMED_OBJECT_UNKNOWN:
7274       return this->unknown_value()->location();
7275
7276     case NAMED_OBJECT_CONST:
7277       return this->const_value()->location();
7278
7279     case NAMED_OBJECT_TYPE:
7280       return this->type_value()->location();
7281
7282     case NAMED_OBJECT_TYPE_DECLARATION:
7283       return this->type_declaration_value()->location();
7284
7285     case NAMED_OBJECT_VAR:
7286       return this->var_value()->location();
7287
7288     case NAMED_OBJECT_RESULT_VAR:
7289       return this->result_var_value()->location();
7290
7291     case NAMED_OBJECT_SINK:
7292       go_unreachable();
7293
7294     case NAMED_OBJECT_FUNC:
7295       return this->func_value()->location();
7296
7297     case NAMED_OBJECT_FUNC_DECLARATION:
7298       return this->func_declaration_value()->location();
7299
7300     case NAMED_OBJECT_PACKAGE:
7301       return this->package_value()->location();
7302     }
7303 }
7304
7305 // Export a named object.
7306
7307 void
7308 Named_object::export_named_object(Export* exp) const
7309 {
7310   switch (this->classification_)
7311     {
7312     default:
7313     case NAMED_OBJECT_UNINITIALIZED:
7314     case NAMED_OBJECT_UNKNOWN:
7315       go_unreachable();
7316
7317     case NAMED_OBJECT_ERRONEOUS:
7318       break;
7319
7320     case NAMED_OBJECT_CONST:
7321       this->const_value()->export_const(exp, this->name_);
7322       break;
7323
7324     case NAMED_OBJECT_TYPE:
7325       this->type_value()->export_named_type(exp, this->name_);
7326       break;
7327
7328     case NAMED_OBJECT_TYPE_DECLARATION:
7329       go_error_at(this->type_declaration_value()->location(),
7330                   "attempt to export %<%s%> which was declared but not defined",
7331                   this->message_name().c_str());
7332       break;
7333
7334     case NAMED_OBJECT_FUNC_DECLARATION:
7335       this->func_declaration_value()->export_func(exp, this->name_);
7336       break;
7337
7338     case NAMED_OBJECT_VAR:
7339       this->var_value()->export_var(exp, this->name_);
7340       break;
7341
7342     case NAMED_OBJECT_RESULT_VAR:
7343     case NAMED_OBJECT_SINK:
7344       go_unreachable();
7345
7346     case NAMED_OBJECT_FUNC:
7347       this->func_value()->export_func(exp, this->name_);
7348       break;
7349     }
7350 }
7351
7352 // Convert a variable to the backend representation.
7353
7354 Bvariable*
7355 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
7356 {
7357   if (this->classification_ == NAMED_OBJECT_VAR)
7358     return this->var_value()->get_backend_variable(gogo, function,
7359                                                    this->package_, this->name_);
7360   else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
7361     return this->result_var_value()->get_backend_variable(gogo, function,
7362                                                           this->name_);
7363   else
7364     go_unreachable();
7365 }
7366
7367
7368 // Return the external identifier for this object.
7369
7370 std::string
7371 Named_object::get_id(Gogo* gogo)
7372 {
7373   go_assert(!this->is_variable() && !this->is_result_variable());
7374   std::string decl_name;
7375   if (this->is_function_declaration()
7376       && !this->func_declaration_value()->asm_name().empty())
7377     decl_name = this->func_declaration_value()->asm_name();
7378   else if (this->is_type()
7379            && Linemap::is_predeclared_location(this->type_value()->location()))
7380     {
7381       // We don't need the package name for builtin types.
7382       decl_name = Gogo::unpack_hidden_name(this->name_);
7383     }
7384   else
7385     {
7386       std::string package_name;
7387       if (this->package_ == NULL)
7388         package_name = gogo->package_name();
7389       else
7390         package_name = this->package_->package_name();
7391
7392       // Note that this will be misleading if this is an unexported
7393       // method generated for an embedded imported type.  In that case
7394       // the unexported method should have the package name of the
7395       // package from which it is imported, but we are going to give
7396       // it our package name.  Fixing this would require knowing the
7397       // package name, but we only know the package path.  It might be
7398       // better to use package paths here anyhow.  This doesn't affect
7399       // the assembler code, because we always set that name in
7400       // Function::get_or_make_decl anyhow.  FIXME.
7401
7402       decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
7403
7404       Function_type* fntype;
7405       if (this->is_function())
7406         fntype = this->func_value()->type();
7407       else if (this->is_function_declaration())
7408         fntype = this->func_declaration_value()->type();
7409       else
7410         fntype = NULL;
7411       if (fntype != NULL && fntype->is_method())
7412         {
7413           decl_name.push_back('.');
7414           decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
7415         }
7416     }
7417   if (this->is_type())
7418     {
7419       unsigned int index;
7420       const Named_object* in_function = this->type_value()->in_function(&index);
7421       if (in_function != NULL)
7422         {
7423           decl_name += '$' + Gogo::unpack_hidden_name(in_function->name());
7424           if (index > 0)
7425             {
7426               char buf[30];
7427               snprintf(buf, sizeof buf, "%u", index);
7428               decl_name += '$';
7429               decl_name += buf;
7430             }
7431         }
7432     }
7433   return decl_name;
7434 }
7435
7436 // Get the backend representation for this named object.
7437
7438 void
7439 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
7440                           std::vector<Btype*>& type_decls,
7441                           std::vector<Bfunction*>& func_decls)
7442 {
7443   // If this is a definition, avoid trying to get the backend
7444   // representation, as that can crash.
7445   if (this->is_redefinition_)
7446     {
7447       go_assert(saw_errors());
7448       return;
7449     }
7450
7451   switch (this->classification_)
7452     {
7453     case NAMED_OBJECT_CONST:
7454       if (!Gogo::is_erroneous_name(this->name_))
7455         const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
7456       break;
7457
7458     case NAMED_OBJECT_TYPE:
7459       {
7460         Named_type* named_type = this->u_.type_value;
7461         if (!Gogo::is_erroneous_name(this->name_))
7462           type_decls.push_back(named_type->get_backend(gogo));
7463
7464         // We need to produce a type descriptor for every named
7465         // type, and for a pointer to every named type, since
7466         // other files or packages might refer to them.  We need
7467         // to do this even for hidden types, because they might
7468         // still be returned by some function.  Simply calling the
7469         // type_descriptor method is enough to create the type
7470         // descriptor, even though we don't do anything with it.
7471         if (this->package_ == NULL && !saw_errors())
7472           {
7473             named_type->
7474                 type_descriptor_pointer(gogo, Linemap::predeclared_location());
7475             named_type->gc_symbol_pointer(gogo);
7476             Type* pn = Type::make_pointer_type(named_type);
7477             pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
7478             pn->gc_symbol_pointer(gogo);
7479           }
7480       }
7481       break;
7482
7483     case NAMED_OBJECT_TYPE_DECLARATION:
7484       go_error_at(Linemap::unknown_location(),
7485                   "reference to undefined type %qs",
7486                   this->message_name().c_str());
7487       return;
7488
7489     case NAMED_OBJECT_VAR:
7490     case NAMED_OBJECT_RESULT_VAR:
7491     case NAMED_OBJECT_SINK:
7492       go_unreachable();
7493
7494     case NAMED_OBJECT_FUNC:
7495       {
7496         Function* func = this->u_.func_value;
7497         if (!Gogo::is_erroneous_name(this->name_))
7498           func_decls.push_back(func->get_or_make_decl(gogo, this));
7499
7500         if (func->block() != NULL)
7501           func->build(gogo, this);
7502       }
7503       break;
7504
7505     case NAMED_OBJECT_ERRONEOUS:
7506       break;
7507
7508     default:
7509       go_unreachable();
7510     }
7511 }
7512
7513 // Class Bindings.
7514
7515 Bindings::Bindings(Bindings* enclosing)
7516   : enclosing_(enclosing), named_objects_(), bindings_()
7517 {
7518 }
7519
7520 // Clear imports.
7521
7522 void
7523 Bindings::clear_file_scope(Gogo* gogo)
7524 {
7525   Contour::iterator p = this->bindings_.begin();
7526   while (p != this->bindings_.end())
7527     {
7528       bool keep;
7529       if (p->second->package() != NULL)
7530         keep = false;
7531       else if (p->second->is_package())
7532         keep = false;
7533       else if (p->second->is_function()
7534                && !p->second->func_value()->type()->is_method()
7535                && Gogo::unpack_hidden_name(p->second->name()) == "init")
7536         keep = false;
7537       else
7538         keep = true;
7539
7540       if (keep)
7541         ++p;
7542       else
7543         {
7544           gogo->add_file_block_name(p->second->name(), p->second->location());
7545           p = this->bindings_.erase(p);
7546         }
7547     }
7548 }
7549
7550 // Look up a symbol.
7551
7552 Named_object*
7553 Bindings::lookup(const std::string& name) const
7554 {
7555   Contour::const_iterator p = this->bindings_.find(name);
7556   if (p != this->bindings_.end())
7557     return p->second->resolve();
7558   else if (this->enclosing_ != NULL)
7559     return this->enclosing_->lookup(name);
7560   else
7561     return NULL;
7562 }
7563
7564 // Look up a symbol locally.
7565
7566 Named_object*
7567 Bindings::lookup_local(const std::string& name) const
7568 {
7569   Contour::const_iterator p = this->bindings_.find(name);
7570   if (p == this->bindings_.end())
7571     return NULL;
7572   return p->second;
7573 }
7574
7575 // Remove an object from a set of bindings.  This is used for a
7576 // special case in thunks for functions which call recover.
7577
7578 void
7579 Bindings::remove_binding(Named_object* no)
7580 {
7581   Contour::iterator pb = this->bindings_.find(no->name());
7582   go_assert(pb != this->bindings_.end());
7583   this->bindings_.erase(pb);
7584   for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
7585        pn != this->named_objects_.end();
7586        ++pn)
7587     {
7588       if (*pn == no)
7589         {
7590           this->named_objects_.erase(pn);
7591           return;
7592         }
7593     }
7594   go_unreachable();
7595 }
7596
7597 // Add a method to the list of objects.  This is not added to the
7598 // lookup table.  This is so that we have a single list of objects
7599 // declared at the top level, which we walk through when it's time to
7600 // convert to trees.
7601
7602 void
7603 Bindings::add_method(Named_object* method)
7604 {
7605   this->named_objects_.push_back(method);
7606 }
7607
7608 // Add a generic Named_object to a Contour.
7609
7610 Named_object*
7611 Bindings::add_named_object_to_contour(Contour* contour,
7612                                       Named_object* named_object)
7613 {
7614   go_assert(named_object == named_object->resolve());
7615   const std::string& name(named_object->name());
7616   go_assert(!Gogo::is_sink_name(name));
7617
7618   std::pair<Contour::iterator, bool> ins =
7619     contour->insert(std::make_pair(name, named_object));
7620   if (!ins.second)
7621     {
7622       // The name was already there.
7623       if (named_object->package() != NULL
7624           && ins.first->second->package() == named_object->package()
7625           && (ins.first->second->classification()
7626               == named_object->classification()))
7627         {
7628           // This is a second import of the same object.
7629           return ins.first->second;
7630         }
7631       ins.first->second = this->new_definition(ins.first->second,
7632                                                named_object);
7633       return ins.first->second;
7634     }
7635   else
7636     {
7637       // Don't push declarations on the list.  We push them on when
7638       // and if we find the definitions.  That way we genericize the
7639       // functions in order.
7640       if (!named_object->is_type_declaration()
7641           && !named_object->is_function_declaration()
7642           && !named_object->is_unknown())
7643         this->named_objects_.push_back(named_object);
7644       return named_object;
7645     }
7646 }
7647
7648 // We had an existing named object OLD_OBJECT, and we've seen a new
7649 // one NEW_OBJECT with the same name.  FIXME: This does not free the
7650 // new object when we don't need it.
7651
7652 Named_object*
7653 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
7654 {
7655   if (new_object->is_erroneous() && !old_object->is_erroneous())
7656     return new_object;
7657
7658   std::string reason;
7659   switch (old_object->classification())
7660     {
7661     default:
7662     case Named_object::NAMED_OBJECT_UNINITIALIZED:
7663       go_unreachable();
7664
7665     case Named_object::NAMED_OBJECT_ERRONEOUS:
7666       return old_object;
7667
7668     case Named_object::NAMED_OBJECT_UNKNOWN:
7669       {
7670         Named_object* real = old_object->unknown_value()->real_named_object();
7671         if (real != NULL)
7672           return this->new_definition(real, new_object);
7673         go_assert(!new_object->is_unknown());
7674         old_object->unknown_value()->set_real_named_object(new_object);
7675         if (!new_object->is_type_declaration()
7676             && !new_object->is_function_declaration())
7677           this->named_objects_.push_back(new_object);
7678         return new_object;
7679       }
7680
7681     case Named_object::NAMED_OBJECT_CONST:
7682       break;
7683
7684     case Named_object::NAMED_OBJECT_TYPE:
7685       if (new_object->is_type_declaration())
7686         return old_object;
7687       break;
7688
7689     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7690       if (new_object->is_type_declaration())
7691         return old_object;
7692       if (new_object->is_type())
7693         {
7694           old_object->set_type_value(new_object->type_value());
7695           new_object->type_value()->set_named_object(old_object);
7696           this->named_objects_.push_back(old_object);
7697           return old_object;
7698         }
7699       break;
7700
7701     case Named_object::NAMED_OBJECT_VAR:
7702     case Named_object::NAMED_OBJECT_RESULT_VAR:
7703       // We have already given an error in the parser for cases where
7704       // one parameter or result variable redeclares another one.
7705       if ((new_object->is_variable()
7706            && new_object->var_value()->is_parameter())
7707           || new_object->is_result_variable())
7708         return old_object;
7709       break;
7710
7711     case Named_object::NAMED_OBJECT_SINK:
7712       go_unreachable();
7713
7714     case Named_object::NAMED_OBJECT_FUNC:
7715       if (new_object->is_function_declaration())
7716         {
7717           if (!new_object->func_declaration_value()->asm_name().empty())
7718             go_error_at(Linemap::unknown_location(),
7719                         ("sorry, not implemented: "
7720                          "__asm__ for function definitions"));
7721           Function_type* old_type = old_object->func_value()->type();
7722           Function_type* new_type =
7723             new_object->func_declaration_value()->type();
7724           if (old_type->is_valid_redeclaration(new_type, &reason))
7725             return old_object;
7726         }
7727       break;
7728
7729     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7730       {
7731         if (new_object->is_function())
7732           {
7733             Function_type* old_type =
7734                 old_object->func_declaration_value()->type();
7735             Function_type* new_type = new_object->func_value()->type();
7736             if (old_type->is_valid_redeclaration(new_type, &reason))
7737               {
7738                 if (!old_object->func_declaration_value()->asm_name().empty())
7739                   go_error_at(Linemap::unknown_location(),
7740                               ("sorry, not implemented: "
7741                                "__asm__ for function definitions"));
7742                 old_object->set_function_value(new_object->func_value());
7743                 this->named_objects_.push_back(old_object);
7744                 return old_object;
7745               }
7746           }
7747       }
7748       break;
7749
7750     case Named_object::NAMED_OBJECT_PACKAGE:
7751       break;
7752     }
7753
7754   std::string n = old_object->message_name();
7755   if (reason.empty())
7756     go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
7757   else
7758     go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
7759                 reason.c_str());
7760   old_object->set_is_redefinition();
7761   new_object->set_is_redefinition();
7762
7763   go_inform(old_object->location(), "previous definition of %qs was here",
7764             n.c_str());
7765
7766   return old_object;
7767 }
7768
7769 // Add a named type.
7770
7771 Named_object*
7772 Bindings::add_named_type(Named_type* named_type)
7773 {
7774   return this->add_named_object(named_type->named_object());
7775 }
7776
7777 // Add a function.
7778
7779 Named_object*
7780 Bindings::add_function(const std::string& name, const Package* package,
7781                        Function* function)
7782 {
7783   return this->add_named_object(Named_object::make_function(name, package,
7784                                                             function));
7785 }
7786
7787 // Add a function declaration.
7788
7789 Named_object*
7790 Bindings::add_function_declaration(const std::string& name,
7791                                    const Package* package,
7792                                    Function_type* type,
7793                                    Location location)
7794 {
7795   Named_object* no = Named_object::make_function_declaration(name, package,
7796                                                              type, location);
7797   return this->add_named_object(no);
7798 }
7799
7800 // Define a type which was previously declared.
7801
7802 void
7803 Bindings::define_type(Named_object* no, Named_type* type)
7804 {
7805   no->set_type_value(type);
7806   this->named_objects_.push_back(no);
7807 }
7808
7809 // Mark all local variables as used.  This is used for some types of
7810 // parse error.
7811
7812 void
7813 Bindings::mark_locals_used()
7814 {
7815   for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
7816        p != this->named_objects_.end();
7817        ++p)
7818     if ((*p)->is_variable())
7819       (*p)->var_value()->set_is_used();
7820 }
7821
7822 // Traverse bindings.
7823
7824 int
7825 Bindings::traverse(Traverse* traverse, bool is_global)
7826 {
7827   unsigned int traverse_mask = traverse->traverse_mask();
7828
7829   // We don't use an iterator because we permit the traversal to add
7830   // new global objects.
7831   const unsigned int e_or_t = (Traverse::traverse_expressions
7832                                | Traverse::traverse_types);
7833   const unsigned int e_or_t_or_s = (e_or_t
7834                                     | Traverse::traverse_statements);
7835   for (size_t i = 0; i < this->named_objects_.size(); ++i)
7836     {
7837       Named_object* p = this->named_objects_[i];
7838       int t = TRAVERSE_CONTINUE;
7839       switch (p->classification())
7840         {
7841         case Named_object::NAMED_OBJECT_CONST:
7842           if ((traverse_mask & Traverse::traverse_constants) != 0)
7843             t = traverse->constant(p, is_global);
7844           if (t == TRAVERSE_CONTINUE
7845               && (traverse_mask & e_or_t) != 0)
7846             {
7847               Type* tc = p->const_value()->type();
7848               if (tc != NULL
7849                   && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
7850                 return TRAVERSE_EXIT;
7851               t = p->const_value()->traverse_expression(traverse);
7852             }
7853           break;
7854
7855         case Named_object::NAMED_OBJECT_VAR:
7856         case Named_object::NAMED_OBJECT_RESULT_VAR:
7857           if ((traverse_mask & Traverse::traverse_variables) != 0)
7858             t = traverse->variable(p);
7859           if (t == TRAVERSE_CONTINUE
7860               && (traverse_mask & e_or_t) != 0)
7861             {
7862               if (p->is_result_variable()
7863                   || p->var_value()->has_type())
7864                 {
7865                   Type* tv = (p->is_variable()
7866                               ? p->var_value()->type()
7867                               : p->result_var_value()->type());
7868                   if (tv != NULL
7869                       && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
7870                     return TRAVERSE_EXIT;
7871                 }
7872             }
7873           if (t == TRAVERSE_CONTINUE
7874               && (traverse_mask & e_or_t_or_s) != 0
7875               && p->is_variable())
7876             t = p->var_value()->traverse_expression(traverse, traverse_mask);
7877           break;
7878
7879         case Named_object::NAMED_OBJECT_FUNC:
7880           if ((traverse_mask & Traverse::traverse_functions) != 0)
7881             t = traverse->function(p);
7882
7883           if (t == TRAVERSE_CONTINUE
7884               && (traverse_mask
7885                   & (Traverse::traverse_variables
7886                      | Traverse::traverse_constants
7887                      | Traverse::traverse_functions
7888                      | Traverse::traverse_blocks
7889                      | Traverse::traverse_statements
7890                      | Traverse::traverse_expressions
7891                      | Traverse::traverse_types)) != 0)
7892             t = p->func_value()->traverse(traverse);
7893           break;
7894
7895         case Named_object::NAMED_OBJECT_PACKAGE:
7896           // These are traversed in Gogo::traverse.
7897           go_assert(is_global);
7898           break;
7899
7900         case Named_object::NAMED_OBJECT_TYPE:
7901           if ((traverse_mask & e_or_t) != 0)
7902             t = Type::traverse(p->type_value(), traverse);
7903           break;
7904
7905         case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7906         case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7907         case Named_object::NAMED_OBJECT_UNKNOWN:
7908         case Named_object::NAMED_OBJECT_ERRONEOUS:
7909           break;
7910
7911         case Named_object::NAMED_OBJECT_SINK:
7912         default:
7913           go_unreachable();
7914         }
7915
7916       if (t == TRAVERSE_EXIT)
7917         return TRAVERSE_EXIT;
7918     }
7919
7920   // If we need to traverse types, check the function declarations,
7921   // which have types.  Also check any methods of a type declaration.
7922   if ((traverse_mask & e_or_t) != 0)
7923     {
7924       for (Bindings::const_declarations_iterator p =
7925              this->begin_declarations();
7926            p != this->end_declarations();
7927            ++p)
7928         {
7929           if (p->second->is_function_declaration())
7930             {
7931               if (Type::traverse(p->second->func_declaration_value()->type(),
7932                                  traverse)
7933                   == TRAVERSE_EXIT)
7934                 return TRAVERSE_EXIT;
7935             }
7936           else if (p->second->is_type_declaration())
7937             {
7938               const std::vector<Named_object*>* methods =
7939                 p->second->type_declaration_value()->methods();
7940               for (std::vector<Named_object*>::const_iterator pm =
7941                      methods->begin();
7942                    pm != methods->end();
7943                    pm++)
7944                 {
7945                   Named_object* no = *pm;
7946                   Type *t;
7947                   if (no->is_function())
7948                     t = no->func_value()->type();
7949                   else if (no->is_function_declaration())
7950                     t = no->func_declaration_value()->type();
7951                   else
7952                     continue;
7953                   if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
7954                     return TRAVERSE_EXIT;
7955                 }
7956             }
7957         }
7958     }
7959
7960   return TRAVERSE_CONTINUE;
7961 }
7962
7963 // Class Label.
7964
7965 // Clear any references to this label.
7966
7967 void
7968 Label::clear_refs()
7969 {
7970   for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
7971        p != this->refs_.end();
7972        ++p)
7973     delete *p;
7974   this->refs_.clear();
7975 }
7976
7977 // Get the backend representation for a label.
7978
7979 Blabel*
7980 Label::get_backend_label(Translate_context* context)
7981 {
7982   if (this->blabel_ == NULL)
7983     {
7984       Function* function = context->function()->func_value();
7985       Bfunction* bfunction = function->get_decl();
7986       this->blabel_ = context->backend()->label(bfunction, this->name_,
7987                                                 this->location_);
7988     }
7989   return this->blabel_;
7990 }
7991
7992 // Return an expression for the address of this label.
7993
7994 Bexpression*
7995 Label::get_addr(Translate_context* context, Location location)
7996 {
7997   Blabel* label = this->get_backend_label(context);
7998   return context->backend()->label_address(label, location);
7999 }
8000
8001 // Return the dummy label that represents any instance of the blank label.
8002
8003 Label*
8004 Label::create_dummy_label()
8005 {
8006   static Label* dummy_label;
8007   if (dummy_label == NULL)
8008     {
8009       dummy_label = new Label("_");
8010       dummy_label->set_is_used();
8011     }
8012   return dummy_label;
8013 }
8014
8015 // Class Unnamed_label.
8016
8017 // Get the backend representation for an unnamed label.
8018
8019 Blabel*
8020 Unnamed_label::get_blabel(Translate_context* context)
8021 {
8022   if (this->blabel_ == NULL)
8023     {
8024       Function* function = context->function()->func_value();
8025       Bfunction* bfunction = function->get_decl();
8026       this->blabel_ = context->backend()->label(bfunction, "",
8027                                                 this->location_);
8028     }
8029   return this->blabel_;
8030 }
8031
8032 // Return a statement which defines this unnamed label.
8033
8034 Bstatement*
8035 Unnamed_label::get_definition(Translate_context* context)
8036 {
8037   Blabel* blabel = this->get_blabel(context);
8038   return context->backend()->label_definition_statement(blabel);
8039 }
8040
8041 // Return a goto statement to this unnamed label.
8042
8043 Bstatement*
8044 Unnamed_label::get_goto(Translate_context* context, Location location)
8045 {
8046   Blabel* blabel = this->get_blabel(context);
8047   return context->backend()->goto_statement(blabel, location);
8048 }
8049
8050 // Class Package.
8051
8052 Package::Package(const std::string& pkgpath,
8053                  const std::string& pkgpath_symbol, Location location)
8054   : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
8055     package_name_(), bindings_(new Bindings(NULL)),
8056     location_(location)
8057 {
8058   go_assert(!pkgpath.empty());
8059 }
8060
8061 // Set the package name.
8062
8063 void
8064 Package::set_package_name(const std::string& package_name, Location location)
8065 {
8066   go_assert(!package_name.empty());
8067   if (this->package_name_.empty())
8068     this->package_name_ = package_name;
8069   else if (this->package_name_ != package_name)
8070     go_error_at(location,
8071                 ("saw two different packages with "
8072                  "the same package path %s: %s, %s"),
8073                 this->pkgpath_.c_str(), this->package_name_.c_str(),
8074                 package_name.c_str());
8075 }
8076
8077 // Return the pkgpath symbol, which is a prefix for symbols defined in
8078 // this package.
8079
8080 std::string
8081 Package::pkgpath_symbol() const
8082 {
8083   if (this->pkgpath_symbol_.empty())
8084     return Gogo::pkgpath_for_symbol(this->pkgpath_);
8085   return this->pkgpath_symbol_;
8086 }
8087
8088 // Set the package path symbol.
8089
8090 void
8091 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
8092 {
8093   go_assert(!pkgpath_symbol.empty());
8094   if (this->pkgpath_symbol_.empty())
8095     this->pkgpath_symbol_ = pkgpath_symbol;
8096   else
8097     go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
8098 }
8099
8100 // Note that symbol from this package was and qualified by ALIAS.
8101
8102 void
8103 Package::note_usage(const std::string& alias) const
8104 {
8105   Aliases::const_iterator p = this->aliases_.find(alias);
8106   go_assert(p != this->aliases_.end());
8107   p->second->note_usage();
8108 }
8109
8110 // Forget a given usage.  If forgetting this usage means this package becomes
8111 // unused, report that error.
8112
8113 void
8114 Package::forget_usage(Expression* usage) const
8115 {
8116   if (this->fake_uses_.empty())
8117     return;
8118
8119   std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
8120   go_assert(p != this->fake_uses_.end());
8121   this->fake_uses_.erase(p);
8122
8123   if (this->fake_uses_.empty())
8124     go_error_at(this->location(), "imported and not used: %s",
8125                 Gogo::message_name(this->package_name()).c_str());
8126 }
8127
8128 // Clear the used field for the next file.  If the only usages of this package
8129 // are possibly fake, keep the fake usages for lowering.
8130
8131 void
8132 Package::clear_used()
8133 {
8134   std::string dot_alias = "." + this->package_name();
8135   Aliases::const_iterator p = this->aliases_.find(dot_alias);
8136   if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
8137     this->fake_uses_.clear();
8138
8139   this->aliases_.clear();
8140 }
8141
8142 Package_alias*
8143 Package::add_alias(const std::string& alias, Location location)
8144 {
8145   Aliases::const_iterator p = this->aliases_.find(alias);
8146   if (p == this->aliases_.end())
8147     {
8148       std::pair<Aliases::iterator, bool> ret;
8149       ret = this->aliases_.insert(std::make_pair(alias,
8150                                                  new Package_alias(location)));
8151       p = ret.first;
8152     }
8153   return p->second;
8154 }
8155
8156 // Determine types of constants.  Everything else in a package
8157 // (variables, function declarations) should already have a fixed
8158 // type.  Constants may have abstract types.
8159
8160 void
8161 Package::determine_types()
8162 {
8163   Bindings* bindings = this->bindings_;
8164   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
8165        p != bindings->end_definitions();
8166        ++p)
8167     {
8168       if ((*p)->is_const())
8169         (*p)->const_value()->determine_type();
8170     }
8171 }
8172
8173 // Class Traverse.
8174
8175 // Destructor.
8176
8177 Traverse::~Traverse()
8178 {
8179   if (this->types_seen_ != NULL)
8180     delete this->types_seen_;
8181   if (this->expressions_seen_ != NULL)
8182     delete this->expressions_seen_;
8183 }
8184
8185 // Record that we are looking at a type, and return true if we have
8186 // already seen it.
8187
8188 bool
8189 Traverse::remember_type(const Type* type)
8190 {
8191   if (type->is_error_type())
8192     return true;
8193   go_assert((this->traverse_mask() & traverse_types) != 0
8194              || (this->traverse_mask() & traverse_expressions) != 0);
8195   // We mostly only have to remember named types.  But it turns out
8196   // that an interface type can refer to itself without using a name
8197   // by relying on interface inheritance, as in
8198   // type I interface { F() interface{I} }
8199   if (type->classification() != Type::TYPE_NAMED
8200       && type->classification() != Type::TYPE_INTERFACE)
8201     return false;
8202   if (this->types_seen_ == NULL)
8203     this->types_seen_ = new Types_seen();
8204   std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
8205   return !ins.second;
8206 }
8207
8208 // Record that we are looking at an expression, and return true if we
8209 // have already seen it. NB: this routine used to assert if the traverse
8210 // mask did not include expressions/types -- this is no longer the case,
8211 // since it can be useful to remember specific expressions during
8212 // walks that only cover statements.
8213
8214 bool
8215 Traverse::remember_expression(const Expression* expression)
8216 {
8217   if (this->expressions_seen_ == NULL)
8218     this->expressions_seen_ = new Expressions_seen();
8219   std::pair<Expressions_seen::iterator, bool> ins =
8220     this->expressions_seen_->insert(expression);
8221   return !ins.second;
8222 }
8223
8224 // The default versions of these functions should never be called: the
8225 // traversal mask indicates which functions may be called.
8226
8227 int
8228 Traverse::variable(Named_object*)
8229 {
8230   go_unreachable();
8231 }
8232
8233 int
8234 Traverse::constant(Named_object*, bool)
8235 {
8236   go_unreachable();
8237 }
8238
8239 int
8240 Traverse::function(Named_object*)
8241 {
8242   go_unreachable();
8243 }
8244
8245 int
8246 Traverse::block(Block*)
8247 {
8248   go_unreachable();
8249 }
8250
8251 int
8252 Traverse::statement(Block*, size_t*, Statement*)
8253 {
8254   go_unreachable();
8255 }
8256
8257 int
8258 Traverse::expression(Expression**)
8259 {
8260   go_unreachable();
8261 }
8262
8263 int
8264 Traverse::type(Type*)
8265 {
8266   go_unreachable();
8267 }
8268
8269 // Class Statement_inserter.
8270
8271 void
8272 Statement_inserter::insert(Statement* s)
8273 {
8274   if (this->block_ != NULL)
8275     {
8276       go_assert(this->pindex_ != NULL);
8277       this->block_->insert_statement_before(*this->pindex_, s);
8278       ++*this->pindex_;
8279     }
8280   else if (this->var_ != NULL)
8281     this->var_->add_preinit_statement(this->gogo_, s);
8282   else
8283     go_assert(saw_errors());
8284 }