OSDN Git Service

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