OSDN Git Service

fa61808ec3cdcf8e7c4d81b3b9b79956725de074
[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   Struct_type* st = type->struct_type();
2876   if (nt != NULL || st != NULL)
2877     {
2878       for (std::vector<Interface_type*>::const_iterator p =
2879              this->interfaces_.begin();
2880            p != this->interfaces_.end();
2881            ++p)
2882         {
2883           // We ask whether a pointer to the named type implements the
2884           // interface, because a pointer can implement more methods
2885           // than a value.
2886           if (nt != NULL)
2887             {
2888               if ((*p)->implements_interface(Type::make_pointer_type(nt),
2889                                              NULL))
2890                 {
2891                   nt->interface_method_table(this->gogo_, *p, false);
2892                   nt->interface_method_table(this->gogo_, *p, true);
2893                 }
2894             }
2895           else
2896             {
2897               if ((*p)->implements_interface(Type::make_pointer_type(st),
2898                                              NULL))
2899                 {
2900                   st->interface_method_table(this->gogo_, *p, false);
2901                   st->interface_method_table(this->gogo_, *p, true);
2902                 }
2903             }
2904         }
2905     }
2906   return TRAVERSE_CONTINUE;
2907 }
2908
2909 // Traversal class used to check for return statements.
2910
2911 class Check_return_statements_traverse : public Traverse
2912 {
2913  public:
2914   Check_return_statements_traverse()
2915     : Traverse(traverse_functions)
2916   { }
2917
2918   int
2919   function(Named_object*);
2920 };
2921
2922 // Check that a function has a return statement if it needs one.
2923
2924 int
2925 Check_return_statements_traverse::function(Named_object* no)
2926 {
2927   Function* func = no->func_value();
2928   const Function_type* fntype = func->type();
2929   const Typed_identifier_list* results = fntype->results();
2930
2931   // We only need a return statement if there is a return value.
2932   if (results == NULL || results->empty())
2933     return TRAVERSE_CONTINUE;
2934
2935   if (func->block()->may_fall_through())
2936     error_at(func->location(), "control reaches end of non-void function");
2937
2938   return TRAVERSE_CONTINUE;
2939 }
2940
2941 // Check return statements.
2942
2943 void
2944 Gogo::check_return_statements()
2945 {
2946   Check_return_statements_traverse traverse;
2947   this->traverse(&traverse);
2948 }
2949
2950 // Work out the package priority.  It is one more than the maximum
2951 // priority of an imported package.
2952
2953 int
2954 Gogo::package_priority() const
2955 {
2956   int priority = 0;
2957   for (Packages::const_iterator p = this->packages_.begin();
2958        p != this->packages_.end();
2959        ++p)
2960     if (p->second->priority() > priority)
2961       priority = p->second->priority();
2962   return priority + 1;
2963 }
2964
2965 // Export identifiers as requested.
2966
2967 void
2968 Gogo::do_exports()
2969 {
2970   // For now we always stream to a section.  Later we may want to
2971   // support streaming to a separate file.
2972   Stream_to_section stream;
2973
2974   Export exp(&stream);
2975   exp.register_builtin_types(this);
2976   exp.export_globals(this->package_name(),
2977                      this->pkgpath(),
2978                      this->package_priority(),
2979                      this->imports_,
2980                      (this->need_init_fn_ && !this->is_main_package()
2981                       ? this->get_init_fn_name()
2982                       : ""),
2983                      this->imported_init_fns_,
2984                      this->package_->bindings());
2985 }
2986
2987 // Find the blocks in order to convert named types defined in blocks.
2988
2989 class Convert_named_types : public Traverse
2990 {
2991  public:
2992   Convert_named_types(Gogo* gogo)
2993     : Traverse(traverse_blocks),
2994       gogo_(gogo)
2995   { }
2996
2997  protected:
2998   int
2999   block(Block* block);
3000
3001  private:
3002   Gogo* gogo_;
3003 };
3004
3005 int
3006 Convert_named_types::block(Block* block)
3007 {
3008   this->gogo_->convert_named_types_in_bindings(block->bindings());
3009   return TRAVERSE_CONTINUE;
3010 }
3011
3012 // Convert all named types to the backend representation.  Since named
3013 // types can refer to other types, this needs to be done in the right
3014 // sequence, which is handled by Named_type::convert.  Here we arrange
3015 // to call that for each named type.
3016
3017 void
3018 Gogo::convert_named_types()
3019 {
3020   this->convert_named_types_in_bindings(this->globals_);
3021   for (Packages::iterator p = this->packages_.begin();
3022        p != this->packages_.end();
3023        ++p)
3024     {
3025       Package* package = p->second;
3026       this->convert_named_types_in_bindings(package->bindings());
3027     }
3028
3029   Convert_named_types cnt(this);
3030   this->traverse(&cnt);
3031
3032   // Make all the builtin named types used for type descriptors, and
3033   // then convert them.  They will only be written out if they are
3034   // needed.
3035   Type::make_type_descriptor_type();
3036   Type::make_type_descriptor_ptr_type();
3037   Function_type::make_function_type_descriptor_type();
3038   Pointer_type::make_pointer_type_descriptor_type();
3039   Struct_type::make_struct_type_descriptor_type();
3040   Array_type::make_array_type_descriptor_type();
3041   Array_type::make_slice_type_descriptor_type();
3042   Map_type::make_map_type_descriptor_type();
3043   Map_type::make_map_descriptor_type();
3044   Channel_type::make_chan_type_descriptor_type();
3045   Interface_type::make_interface_type_descriptor_type();
3046   Type::convert_builtin_named_types(this);
3047
3048   Runtime::convert_types(this);
3049
3050   this->named_types_are_converted_ = true;
3051 }
3052
3053 // Convert all names types in a set of bindings.
3054
3055 void
3056 Gogo::convert_named_types_in_bindings(Bindings* bindings)
3057 {
3058   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3059        p != bindings->end_definitions();
3060        ++p)
3061     {
3062       if ((*p)->is_type())
3063         (*p)->type_value()->convert(this);
3064     }
3065 }
3066
3067 // Class Function.
3068
3069 Function::Function(Function_type* type, Function* enclosing, Block* block,
3070                    Location location)
3071   : type_(type), enclosing_(enclosing), results_(NULL),
3072     closure_var_(NULL), block_(block), location_(location), labels_(),
3073     local_type_count_(0), fndecl_(NULL), defer_stack_(NULL),
3074     results_are_named_(false), calls_recover_(false), is_recover_thunk_(false),
3075     has_recover_thunk_(false)
3076 {
3077 }
3078
3079 // Create the named result variables.
3080
3081 void
3082 Function::create_result_variables(Gogo* gogo)
3083 {
3084   const Typed_identifier_list* results = this->type_->results();
3085   if (results == NULL || results->empty())
3086     return;
3087
3088   if (!results->front().name().empty())
3089     this->results_are_named_ = true;
3090
3091   this->results_ = new Results();
3092   this->results_->reserve(results->size());
3093
3094   Block* block = this->block_;
3095   int index = 0;
3096   for (Typed_identifier_list::const_iterator p = results->begin();
3097        p != results->end();
3098        ++p, ++index)
3099     {
3100       std::string name = p->name();
3101       if (name.empty() || Gogo::is_sink_name(name))
3102         {
3103           static int result_counter;
3104           char buf[100];
3105           snprintf(buf, sizeof buf, "$ret%d", result_counter);
3106           ++result_counter;
3107           name = gogo->pack_hidden_name(buf, false);
3108         }
3109       Result_variable* result = new Result_variable(p->type(), this, index,
3110                                                     p->location());
3111       Named_object* no = block->bindings()->add_result_variable(name, result);
3112       if (no->is_result_variable())
3113         this->results_->push_back(no);
3114       else
3115         {
3116           static int dummy_result_count;
3117           char buf[100];
3118           snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
3119           ++dummy_result_count;
3120           name = gogo->pack_hidden_name(buf, false);
3121           no = block->bindings()->add_result_variable(name, result);
3122           go_assert(no->is_result_variable());
3123           this->results_->push_back(no);
3124         }
3125     }
3126 }
3127
3128 // Update the named result variables when cloning a function which
3129 // calls recover.
3130
3131 void
3132 Function::update_result_variables()
3133 {
3134   if (this->results_ == NULL)
3135     return;
3136
3137   for (Results::iterator p = this->results_->begin();
3138        p != this->results_->end();
3139        ++p)
3140     (*p)->result_var_value()->set_function(this);
3141 }
3142
3143 // Return the closure variable, creating it if necessary.
3144
3145 Named_object*
3146 Function::closure_var()
3147 {
3148   if (this->closure_var_ == NULL)
3149     {
3150       // We don't know the type of the variable yet.  We add fields as
3151       // we find them.
3152       Location loc = this->type_->location();
3153       Struct_field_list* sfl = new Struct_field_list;
3154       Type* struct_type = Type::make_struct_type(sfl, loc);
3155       Variable* var = new Variable(Type::make_pointer_type(struct_type),
3156                                    NULL, false, true, false, loc);
3157       var->set_is_used();
3158       this->closure_var_ = Named_object::make_variable("closure", NULL, var);
3159       // Note that the new variable is not in any binding contour.
3160     }
3161   return this->closure_var_;
3162 }
3163
3164 // Set the type of the closure variable.
3165
3166 void
3167 Function::set_closure_type()
3168 {
3169   if (this->closure_var_ == NULL)
3170     return;
3171   Named_object* closure = this->closure_var_;
3172   Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3173   unsigned int index = 0;
3174   for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3175        p != this->closure_fields_.end();
3176        ++p, ++index)
3177     {
3178       Named_object* no = p->first;
3179       char buf[20];
3180       snprintf(buf, sizeof buf, "%u", index);
3181       std::string n = no->name() + buf;
3182       Type* var_type;
3183       if (no->is_variable())
3184         var_type = no->var_value()->type();
3185       else
3186         var_type = no->result_var_value()->type();
3187       Type* field_type = Type::make_pointer_type(var_type);
3188       st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3189     }
3190 }
3191
3192 // Return whether this function is a method.
3193
3194 bool
3195 Function::is_method() const
3196 {
3197   return this->type_->is_method();
3198 }
3199
3200 // Add a label definition.
3201
3202 Label*
3203 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3204                                Location location)
3205 {
3206   Label* lnull = NULL;
3207   std::pair<Labels::iterator, bool> ins =
3208     this->labels_.insert(std::make_pair(label_name, lnull));
3209   Label* label;
3210   if (ins.second)
3211     {
3212       // This is a new label.
3213       label = new Label(label_name);
3214       ins.first->second = label;
3215     }
3216   else
3217     {
3218       // The label was already in the hash table.
3219       label = ins.first->second;
3220       if (label->is_defined())
3221         {
3222           error_at(location, "label %qs already defined",
3223                    Gogo::message_name(label_name).c_str());
3224           inform(label->location(), "previous definition of %qs was here",
3225                  Gogo::message_name(label_name).c_str());
3226           return new Label(label_name);
3227         }
3228     }
3229
3230   label->define(location, gogo->bindings_snapshot(location));
3231
3232   // Issue any errors appropriate for any previous goto's to this
3233   // label.
3234   const std::vector<Bindings_snapshot*>& refs(label->refs());
3235   for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3236        p != refs.end();
3237        ++p)
3238     (*p)->check_goto_to(gogo->current_block());
3239   label->clear_refs();
3240
3241   return label;
3242 }
3243
3244 // Add a reference to a label.
3245
3246 Label*
3247 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3248                               Location location, bool issue_goto_errors)
3249 {
3250   Label* lnull = NULL;
3251   std::pair<Labels::iterator, bool> ins =
3252     this->labels_.insert(std::make_pair(label_name, lnull));
3253   Label* label;
3254   if (!ins.second)
3255     {
3256       // The label was already in the hash table.
3257       label = ins.first->second;
3258     }
3259   else
3260     {
3261       go_assert(ins.first->second == NULL);
3262       label = new Label(label_name);
3263       ins.first->second = label;
3264     }
3265
3266   label->set_is_used();
3267
3268   if (issue_goto_errors)
3269     {
3270       Bindings_snapshot* snapshot = label->snapshot();
3271       if (snapshot != NULL)
3272         snapshot->check_goto_from(gogo->current_block(), location);
3273       else
3274         label->add_snapshot_ref(gogo->bindings_snapshot(location));
3275     }
3276
3277   return label;
3278 }
3279
3280 // Warn about labels that are defined but not used.
3281
3282 void
3283 Function::check_labels() const
3284 {
3285   for (Labels::const_iterator p = this->labels_.begin();
3286        p != this->labels_.end();
3287        p++)
3288     {
3289       Label* label = p->second;
3290       if (!label->is_used())
3291         error_at(label->location(), "label %qs defined and not used",
3292                  Gogo::message_name(label->name()).c_str());
3293     }
3294 }
3295
3296 // Swap one function with another.  This is used when building the
3297 // thunk we use to call a function which calls recover.  It may not
3298 // work for any other case.
3299
3300 void
3301 Function::swap_for_recover(Function *x)
3302 {
3303   go_assert(this->enclosing_ == x->enclosing_);
3304   std::swap(this->results_, x->results_);
3305   std::swap(this->closure_var_, x->closure_var_);
3306   std::swap(this->block_, x->block_);
3307   go_assert(this->location_ == x->location_);
3308   go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3309   go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3310 }
3311
3312 // Traverse the tree.
3313
3314 int
3315 Function::traverse(Traverse* traverse)
3316 {
3317   unsigned int traverse_mask = traverse->traverse_mask();
3318
3319   if ((traverse_mask
3320        & (Traverse::traverse_types | Traverse::traverse_expressions))
3321       != 0)
3322     {
3323       if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3324         return TRAVERSE_EXIT;
3325     }
3326
3327   // FIXME: We should check traverse_functions here if nested
3328   // functions are stored in block bindings.
3329   if (this->block_ != NULL
3330       && (traverse_mask
3331           & (Traverse::traverse_variables
3332              | Traverse::traverse_constants
3333              | Traverse::traverse_blocks
3334              | Traverse::traverse_statements
3335              | Traverse::traverse_expressions
3336              | Traverse::traverse_types)) != 0)
3337     {
3338       if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3339         return TRAVERSE_EXIT;
3340     }
3341
3342   return TRAVERSE_CONTINUE;
3343 }
3344
3345 // Work out types for unspecified variables and constants.
3346
3347 void
3348 Function::determine_types()
3349 {
3350   if (this->block_ != NULL)
3351     this->block_->determine_types();
3352 }
3353
3354 // Get a pointer to the variable representing the defer stack for this
3355 // function, making it if necessary.  The value of the variable is set
3356 // by the runtime routines to true if the function is returning,
3357 // rather than panicing through.  A pointer to this variable is used
3358 // as a marker for the functions on the defer stack associated with
3359 // this function.  A function-specific variable permits inlining a
3360 // function which uses defer.
3361
3362 Expression*
3363 Function::defer_stack(Location location)
3364 {
3365   if (this->defer_stack_ == NULL)
3366     {
3367       Type* t = Type::lookup_bool_type();
3368       Expression* n = Expression::make_boolean(false, location);
3369       this->defer_stack_ = Statement::make_temporary(t, n, location);
3370       this->defer_stack_->set_is_address_taken();
3371     }
3372   Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3373                                                          location);
3374   return Expression::make_unary(OPERATOR_AND, ref, location);
3375 }
3376
3377 // Export the function.
3378
3379 void
3380 Function::export_func(Export* exp, const std::string& name) const
3381 {
3382   Function::export_func_with_type(exp, name, this->type_);
3383 }
3384
3385 // Export a function with a type.
3386
3387 void
3388 Function::export_func_with_type(Export* exp, const std::string& name,
3389                                 const Function_type* fntype)
3390 {
3391   exp->write_c_string("func ");
3392
3393   if (fntype->is_method())
3394     {
3395       exp->write_c_string("(");
3396       const Typed_identifier* receiver = fntype->receiver();
3397       exp->write_name(receiver->name());
3398       exp->write_c_string(" ");
3399       exp->write_type(receiver->type());
3400       exp->write_c_string(") ");
3401     }
3402
3403   exp->write_string(name);
3404
3405   exp->write_c_string(" (");
3406   const Typed_identifier_list* parameters = fntype->parameters();
3407   if (parameters != NULL)
3408     {
3409       bool is_varargs = fntype->is_varargs();
3410       bool first = true;
3411       for (Typed_identifier_list::const_iterator p = parameters->begin();
3412            p != parameters->end();
3413            ++p)
3414         {
3415           if (first)
3416             first = false;
3417           else
3418             exp->write_c_string(", ");
3419           exp->write_name(p->name());
3420           exp->write_c_string(" ");
3421           if (!is_varargs || p + 1 != parameters->end())
3422             exp->write_type(p->type());
3423           else
3424             {
3425               exp->write_c_string("...");
3426               exp->write_type(p->type()->array_type()->element_type());
3427             }
3428         }
3429     }
3430   exp->write_c_string(")");
3431
3432   const Typed_identifier_list* results = fntype->results();
3433   if (results != NULL)
3434     {
3435       if (results->size() == 1 && results->begin()->name().empty())
3436         {
3437           exp->write_c_string(" ");
3438           exp->write_type(results->begin()->type());
3439         }
3440       else
3441         {
3442           exp->write_c_string(" (");
3443           bool first = true;
3444           for (Typed_identifier_list::const_iterator p = results->begin();
3445                p != results->end();
3446                ++p)
3447             {
3448               if (first)
3449                 first = false;
3450               else
3451                 exp->write_c_string(", ");
3452               exp->write_name(p->name());
3453               exp->write_c_string(" ");
3454               exp->write_type(p->type());
3455             }
3456           exp->write_c_string(")");
3457         }
3458     }
3459   exp->write_c_string(";\n");
3460 }
3461
3462 // Import a function.
3463
3464 void
3465 Function::import_func(Import* imp, std::string* pname,
3466                       Typed_identifier** preceiver,
3467                       Typed_identifier_list** pparameters,
3468                       Typed_identifier_list** presults,
3469                       bool* is_varargs)
3470 {
3471   imp->require_c_string("func ");
3472
3473   *preceiver = NULL;
3474   if (imp->peek_char() == '(')
3475     {
3476       imp->require_c_string("(");
3477       std::string name = imp->read_name();
3478       imp->require_c_string(" ");
3479       Type* rtype = imp->read_type();
3480       *preceiver = new Typed_identifier(name, rtype, imp->location());
3481       imp->require_c_string(") ");
3482     }
3483
3484   *pname = imp->read_identifier();
3485
3486   Typed_identifier_list* parameters;
3487   *is_varargs = false;
3488   imp->require_c_string(" (");
3489   if (imp->peek_char() == ')')
3490     parameters = NULL;
3491   else
3492     {
3493       parameters = new Typed_identifier_list();
3494       while (true)
3495         {
3496           std::string name = imp->read_name();
3497           imp->require_c_string(" ");
3498
3499           if (imp->match_c_string("..."))
3500             {
3501               imp->advance(3);
3502               *is_varargs = true;
3503             }
3504
3505           Type* ptype = imp->read_type();
3506           if (*is_varargs)
3507             ptype = Type::make_array_type(ptype, NULL);
3508           parameters->push_back(Typed_identifier(name, ptype,
3509                                                  imp->location()));
3510           if (imp->peek_char() != ',')
3511             break;
3512           go_assert(!*is_varargs);
3513           imp->require_c_string(", ");
3514         }
3515     }
3516   imp->require_c_string(")");
3517   *pparameters = parameters;
3518
3519   Typed_identifier_list* results;
3520   if (imp->peek_char() != ' ')
3521     results = NULL;
3522   else
3523     {
3524       results = new Typed_identifier_list();
3525       imp->require_c_string(" ");
3526       if (imp->peek_char() != '(')
3527         {
3528           Type* rtype = imp->read_type();
3529           results->push_back(Typed_identifier("", rtype, imp->location()));
3530         }
3531       else
3532         {
3533           imp->require_c_string("(");
3534           while (true)
3535             {
3536               std::string name = imp->read_name();
3537               imp->require_c_string(" ");
3538               Type* rtype = imp->read_type();
3539               results->push_back(Typed_identifier(name, rtype,
3540                                                   imp->location()));
3541               if (imp->peek_char() != ',')
3542                 break;
3543               imp->require_c_string(", ");
3544             }
3545           imp->require_c_string(")");
3546         }
3547     }
3548   imp->require_c_string(";\n");
3549   *presults = results;
3550 }
3551
3552 // Class Block.
3553
3554 Block::Block(Block* enclosing, Location location)
3555   : enclosing_(enclosing), statements_(),
3556     bindings_(new Bindings(enclosing == NULL
3557                            ? NULL
3558                            : enclosing->bindings())),
3559     start_location_(location),
3560     end_location_(UNKNOWN_LOCATION)
3561 {
3562 }
3563
3564 // Add a statement to a block.
3565
3566 void
3567 Block::add_statement(Statement* statement)
3568 {
3569   this->statements_.push_back(statement);
3570 }
3571
3572 // Add a statement to the front of a block.  This is slow but is only
3573 // used for reference counts of parameters.
3574
3575 void
3576 Block::add_statement_at_front(Statement* statement)
3577 {
3578   this->statements_.insert(this->statements_.begin(), statement);
3579 }
3580
3581 // Replace a statement in a block.
3582
3583 void
3584 Block::replace_statement(size_t index, Statement* s)
3585 {
3586   go_assert(index < this->statements_.size());
3587   this->statements_[index] = s;
3588 }
3589
3590 // Add a statement before another statement.
3591
3592 void
3593 Block::insert_statement_before(size_t index, Statement* s)
3594 {
3595   go_assert(index < this->statements_.size());
3596   this->statements_.insert(this->statements_.begin() + index, s);
3597 }
3598
3599 // Add a statement after another statement.
3600
3601 void
3602 Block::insert_statement_after(size_t index, Statement* s)
3603 {
3604   go_assert(index < this->statements_.size());
3605   this->statements_.insert(this->statements_.begin() + index + 1, s);
3606 }
3607
3608 // Traverse the tree.
3609
3610 int
3611 Block::traverse(Traverse* traverse)
3612 {
3613   unsigned int traverse_mask = traverse->traverse_mask();
3614
3615   if ((traverse_mask & Traverse::traverse_blocks) != 0)
3616     {
3617       int t = traverse->block(this);
3618       if (t == TRAVERSE_EXIT)
3619         return TRAVERSE_EXIT;
3620       else if (t == TRAVERSE_SKIP_COMPONENTS)
3621         return TRAVERSE_CONTINUE;
3622     }
3623
3624   if ((traverse_mask
3625        & (Traverse::traverse_variables
3626           | Traverse::traverse_constants
3627           | Traverse::traverse_expressions
3628           | Traverse::traverse_types)) != 0)
3629     {
3630       const unsigned int e_or_t = (Traverse::traverse_expressions
3631                                    | Traverse::traverse_types);
3632       const unsigned int e_or_t_or_s = (e_or_t
3633                                         | Traverse::traverse_statements);
3634       for (Bindings::const_definitions_iterator pb =
3635              this->bindings_->begin_definitions();
3636            pb != this->bindings_->end_definitions();
3637            ++pb)
3638         {
3639           int t = TRAVERSE_CONTINUE;
3640           switch ((*pb)->classification())
3641             {
3642             case Named_object::NAMED_OBJECT_CONST:
3643               if ((traverse_mask & Traverse::traverse_constants) != 0)
3644                 t = traverse->constant(*pb, false);
3645               if (t == TRAVERSE_CONTINUE
3646                   && (traverse_mask & e_or_t) != 0)
3647                 {
3648                   Type* tc = (*pb)->const_value()->type();
3649                   if (tc != NULL
3650                       && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3651                     return TRAVERSE_EXIT;
3652                   t = (*pb)->const_value()->traverse_expression(traverse);
3653                 }
3654               break;
3655
3656             case Named_object::NAMED_OBJECT_VAR:
3657             case Named_object::NAMED_OBJECT_RESULT_VAR:
3658               if ((traverse_mask & Traverse::traverse_variables) != 0)
3659                 t = traverse->variable(*pb);
3660               if (t == TRAVERSE_CONTINUE
3661                   && (traverse_mask & e_or_t) != 0)
3662                 {
3663                   if ((*pb)->is_result_variable()
3664                       || (*pb)->var_value()->has_type())
3665                     {
3666                       Type* tv = ((*pb)->is_variable()
3667                                   ? (*pb)->var_value()->type()
3668                                   : (*pb)->result_var_value()->type());
3669                       if (tv != NULL
3670                           && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3671                         return TRAVERSE_EXIT;
3672                     }
3673                 }
3674               if (t == TRAVERSE_CONTINUE
3675                   && (traverse_mask & e_or_t_or_s) != 0
3676                   && (*pb)->is_variable())
3677                 t = (*pb)->var_value()->traverse_expression(traverse,
3678                                                             traverse_mask);
3679               break;
3680
3681             case Named_object::NAMED_OBJECT_FUNC:
3682             case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3683               go_unreachable();
3684
3685             case Named_object::NAMED_OBJECT_TYPE:
3686               if ((traverse_mask & e_or_t) != 0)
3687                 t = Type::traverse((*pb)->type_value(), traverse);
3688               break;
3689
3690             case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3691             case Named_object::NAMED_OBJECT_UNKNOWN:
3692             case Named_object::NAMED_OBJECT_ERRONEOUS:
3693               break;
3694
3695             case Named_object::NAMED_OBJECT_PACKAGE:
3696             case Named_object::NAMED_OBJECT_SINK:
3697               go_unreachable();
3698
3699             default:
3700               go_unreachable();
3701             }
3702
3703           if (t == TRAVERSE_EXIT)
3704             return TRAVERSE_EXIT;
3705         }
3706     }
3707
3708   // No point in checking traverse_mask here--if we got here we always
3709   // want to walk the statements.  The traversal can insert new
3710   // statements before or after the current statement.  Inserting
3711   // statements before the current statement requires updating I via
3712   // the pointer; those statements will not be traversed.  Any new
3713   // statements inserted after the current statement will be traversed
3714   // in their turn.
3715   for (size_t i = 0; i < this->statements_.size(); ++i)
3716     {
3717       if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3718         return TRAVERSE_EXIT;
3719     }
3720
3721   return TRAVERSE_CONTINUE;
3722 }
3723
3724 // Work out types for unspecified variables and constants.
3725
3726 void
3727 Block::determine_types()
3728 {
3729   for (Bindings::const_definitions_iterator pb =
3730          this->bindings_->begin_definitions();
3731        pb != this->bindings_->end_definitions();
3732        ++pb)
3733     {
3734       if ((*pb)->is_variable())
3735         (*pb)->var_value()->determine_type();
3736       else if ((*pb)->is_const())
3737         (*pb)->const_value()->determine_type();
3738     }
3739
3740   for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3741        ps != this->statements_.end();
3742        ++ps)
3743     (*ps)->determine_types();
3744 }
3745
3746 // Return true if the statements in this block may fall through.
3747
3748 bool
3749 Block::may_fall_through() const
3750 {
3751   if (this->statements_.empty())
3752     return true;
3753   return this->statements_.back()->may_fall_through();
3754 }
3755
3756 // Convert a block to the backend representation.
3757
3758 Bblock*
3759 Block::get_backend(Translate_context* context)
3760 {
3761   Gogo* gogo = context->gogo();
3762   Named_object* function = context->function();
3763   std::vector<Bvariable*> vars;
3764   vars.reserve(this->bindings_->size_definitions());
3765   for (Bindings::const_definitions_iterator pv =
3766          this->bindings_->begin_definitions();
3767        pv != this->bindings_->end_definitions();
3768        ++pv)
3769     {
3770       if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3771         vars.push_back((*pv)->get_backend_variable(gogo, function));
3772     }
3773
3774   // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3775   // until we have a proper representation of the init function.
3776   Bfunction* bfunction;
3777   if (function == NULL)
3778     bfunction = NULL;
3779   else
3780     bfunction = tree_to_function(function->func_value()->get_decl());
3781   Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3782                                           vars, this->start_location_,
3783                                           this->end_location_);
3784
3785   Translate_context subcontext(gogo, function, this, ret);
3786   std::vector<Bstatement*> bstatements;
3787   bstatements.reserve(this->statements_.size());
3788   for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3789        p != this->statements_.end();
3790        ++p)
3791     bstatements.push_back((*p)->get_backend(&subcontext));
3792
3793   context->backend()->block_add_statements(ret, bstatements);
3794
3795   return ret;
3796 }
3797
3798 // Class Bindings_snapshot.
3799
3800 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
3801   : block_(b), counts_(), location_(location)
3802 {
3803   while (b != NULL)
3804     {
3805       this->counts_.push_back(b->bindings()->size_definitions());
3806       b = b->enclosing();
3807     }
3808 }
3809
3810 // Report errors appropriate for a goto from B to this.
3811
3812 void
3813 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
3814 {
3815   size_t dummy;
3816   if (!this->check_goto_block(loc, b, this->block_, &dummy))
3817     return;
3818   this->check_goto_defs(loc, this->block_,
3819                         this->block_->bindings()->size_definitions(),
3820                         this->counts_[0]);
3821 }
3822
3823 // Report errors appropriate for a goto from this to B.
3824
3825 void
3826 Bindings_snapshot::check_goto_to(const Block* b)
3827 {
3828   size_t index;
3829   if (!this->check_goto_block(this->location_, this->block_, b, &index))
3830     return;
3831   this->check_goto_defs(this->location_, b, this->counts_[index],
3832                         b->bindings()->size_definitions());
3833 }
3834
3835 // Report errors appropriate for a goto at LOC from BFROM to BTO.
3836 // Return true if all is well, false if we reported an error.  If this
3837 // returns true, it sets *PINDEX to the number of blocks BTO is above
3838 // BFROM.
3839
3840 bool
3841 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
3842                                     const Block* bto, size_t* pindex)
3843 {
3844   // It is an error if BTO is not either BFROM or above BFROM.
3845   size_t index = 0;
3846   for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
3847     {
3848       if (pb == NULL)
3849         {
3850           error_at(loc, "goto jumps into block");
3851           inform(bto->start_location(), "goto target block starts here");
3852           return false;
3853         }
3854     }
3855   *pindex = index;
3856   return true;
3857 }
3858
3859 // Report errors appropriate for a goto at LOC ending at BLOCK, where
3860 // CFROM is the number of names defined at the point of the goto and
3861 // CTO is the number of names defined at the point of the label.
3862
3863 void
3864 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
3865                                    size_t cfrom, size_t cto)
3866 {
3867   if (cfrom < cto)
3868     {
3869       Bindings::const_definitions_iterator p =
3870         block->bindings()->begin_definitions();
3871       for (size_t i = 0; i < cfrom; ++i)
3872         {
3873           go_assert(p != block->bindings()->end_definitions());
3874           ++p;
3875         }
3876       go_assert(p != block->bindings()->end_definitions());
3877
3878       std::string n = (*p)->message_name();
3879       error_at(loc, "goto jumps over declaration of %qs", n.c_str());
3880       inform((*p)->location(), "%qs defined here", n.c_str());
3881     }
3882 }
3883
3884 // Class Variable.
3885
3886 Variable::Variable(Type* type, Expression* init, bool is_global,
3887                    bool is_parameter, bool is_receiver,
3888                    Location location)
3889   : type_(type), init_(init), preinit_(NULL), location_(location),
3890     backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3891     is_receiver_(is_receiver), is_varargs_parameter_(false), is_used_(false),
3892     is_address_taken_(false), is_non_escaping_address_taken_(false),
3893     seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
3894     type_from_range_index_(false), type_from_range_value_(false),
3895     type_from_chan_element_(false), is_type_switch_var_(false),
3896     determined_type_(false)
3897 {
3898   go_assert(type != NULL || init != NULL);
3899   go_assert(!is_parameter || init == NULL);
3900 }
3901
3902 // Traverse the initializer expression.
3903
3904 int
3905 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
3906 {
3907   if (this->preinit_ != NULL)
3908     {
3909       if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3910         return TRAVERSE_EXIT;
3911     }
3912   if (this->init_ != NULL
3913       && ((traverse_mask
3914            & (Traverse::traverse_expressions | Traverse::traverse_types))
3915           != 0))
3916     {
3917       if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3918         return TRAVERSE_EXIT;
3919     }
3920   return TRAVERSE_CONTINUE;
3921 }
3922
3923 // Lower the initialization expression after parsing is complete.
3924
3925 void
3926 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
3927                                 Statement_inserter* inserter)
3928 {
3929   Named_object* dep = gogo->var_depends_on(this);
3930   if (dep != NULL && dep->is_variable())
3931     dep->var_value()->lower_init_expression(gogo, function, inserter);
3932
3933   if (this->init_ != NULL && !this->init_is_lowered_)
3934     {
3935       if (this->seen_)
3936         {
3937           // We will give an error elsewhere, this is just to prevent
3938           // an infinite loop.
3939           return;
3940         }
3941       this->seen_ = true;
3942
3943       Statement_inserter global_inserter;
3944       if (this->is_global_)
3945         {
3946           global_inserter = Statement_inserter(gogo, this);
3947           inserter = &global_inserter;
3948         }
3949
3950       gogo->lower_expression(function, inserter, &this->init_);
3951
3952       this->seen_ = false;
3953
3954       this->init_is_lowered_ = true;
3955     }
3956 }
3957
3958 // Get the preinit block.
3959
3960 Block*
3961 Variable::preinit_block(Gogo* gogo)
3962 {
3963   go_assert(this->is_global_);
3964   if (this->preinit_ == NULL)
3965     this->preinit_ = new Block(NULL, this->location());
3966
3967   // If a global variable has a preinitialization statement, then we
3968   // need to have an initialization function.
3969   gogo->set_need_init_fn();
3970
3971   return this->preinit_;
3972 }
3973
3974 // Add a statement to be run before the initialization expression.
3975
3976 void
3977 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3978 {
3979   Block* b = this->preinit_block(gogo);
3980   b->add_statement(s);
3981   b->set_end_location(s->location());
3982 }
3983
3984 // Whether this variable has a type.
3985
3986 bool
3987 Variable::has_type() const
3988 {
3989   if (this->type_ == NULL)
3990     return false;
3991
3992   // A variable created in a type switch case nil does not actually
3993   // have a type yet.  It will be changed to use the initializer's
3994   // type in determine_type.
3995   if (this->is_type_switch_var_
3996       && this->type_->is_nil_constant_as_type())
3997     return false;
3998
3999   return true;
4000 }
4001
4002 // In an assignment which sets a variable to a tuple of EXPR, return
4003 // the type of the first element of the tuple.
4004
4005 Type*
4006 Variable::type_from_tuple(Expression* expr, bool report_error) const
4007 {
4008   if (expr->map_index_expression() != NULL)
4009     {
4010       Map_type* mt = expr->map_index_expression()->get_map_type();
4011       if (mt == NULL)
4012         return Type::make_error_type();
4013       return mt->val_type();
4014     }
4015   else if (expr->receive_expression() != NULL)
4016     {
4017       Expression* channel = expr->receive_expression()->channel();
4018       Type* channel_type = channel->type();
4019       if (channel_type->channel_type() == NULL)
4020         return Type::make_error_type();
4021       return channel_type->channel_type()->element_type();
4022     }
4023   else
4024     {
4025       if (report_error)
4026         error_at(this->location(), "invalid tuple definition");
4027       return Type::make_error_type();
4028     }
4029 }
4030
4031 // Given EXPR used in a range clause, return either the index type or
4032 // the value type of the range, depending upon GET_INDEX_TYPE.
4033
4034 Type*
4035 Variable::type_from_range(Expression* expr, bool get_index_type,
4036                           bool report_error) const
4037 {
4038   Type* t = expr->type();
4039   if (t->array_type() != NULL
4040       || (t->points_to() != NULL
4041           && t->points_to()->array_type() != NULL
4042           && !t->points_to()->is_slice_type()))
4043     {
4044       if (get_index_type)
4045         return Type::lookup_integer_type("int");
4046       else
4047         return t->deref()->array_type()->element_type();
4048     }
4049   else if (t->is_string_type())
4050     {
4051       if (get_index_type)
4052         return Type::lookup_integer_type("int");
4053       else
4054         return Type::lookup_integer_type("int32");
4055     }
4056   else if (t->map_type() != NULL)
4057     {
4058       if (get_index_type)
4059         return t->map_type()->key_type();
4060       else
4061         return t->map_type()->val_type();
4062     }
4063   else if (t->channel_type() != NULL)
4064     {
4065       if (get_index_type)
4066         return t->channel_type()->element_type();
4067       else
4068         {
4069           if (report_error)
4070             error_at(this->location(),
4071                      "invalid definition of value variable for channel range");
4072           return Type::make_error_type();
4073         }
4074     }
4075   else
4076     {
4077       if (report_error)
4078         error_at(this->location(), "invalid type for range clause");
4079       return Type::make_error_type();
4080     }
4081 }
4082
4083 // EXPR should be a channel.  Return the channel's element type.
4084
4085 Type*
4086 Variable::type_from_chan_element(Expression* expr, bool report_error) const
4087 {
4088   Type* t = expr->type();
4089   if (t->channel_type() != NULL)
4090     return t->channel_type()->element_type();
4091   else
4092     {
4093       if (report_error)
4094         error_at(this->location(), "expected channel");
4095       return Type::make_error_type();
4096     }
4097 }
4098
4099 // Return the type of the Variable.  This may be called before
4100 // Variable::determine_type is called, which means that we may need to
4101 // get the type from the initializer.  FIXME: If we combine lowering
4102 // with type determination, then this should be unnecessary.
4103
4104 Type*
4105 Variable::type()
4106 {
4107   // A variable in a type switch with a nil case will have the wrong
4108   // type here.  This gets fixed up in determine_type, below.
4109   Type* type = this->type_;
4110   Expression* init = this->init_;
4111   if (this->is_type_switch_var_
4112       && this->type_->is_nil_constant_as_type())
4113     {
4114       Type_guard_expression* tge = this->init_->type_guard_expression();
4115       go_assert(tge != NULL);
4116       init = tge->expr();
4117       type = NULL;
4118     }
4119
4120   if (this->seen_)
4121     {
4122       if (this->type_ == NULL || !this->type_->is_error_type())
4123         {
4124           error_at(this->location_, "variable initializer refers to itself");
4125           this->type_ = Type::make_error_type();
4126         }
4127       return this->type_;
4128     }
4129
4130   this->seen_ = true;
4131
4132   if (type != NULL)
4133     ;
4134   else if (this->type_from_init_tuple_)
4135     type = this->type_from_tuple(init, false);
4136   else if (this->type_from_range_index_ || this->type_from_range_value_)
4137     type = this->type_from_range(init, this->type_from_range_index_, false);
4138   else if (this->type_from_chan_element_)
4139     type = this->type_from_chan_element(init, false);
4140   else
4141     {
4142       go_assert(init != NULL);
4143       type = init->type();
4144       go_assert(type != NULL);
4145
4146       // Variables should not have abstract types.
4147       if (type->is_abstract())
4148         type = type->make_non_abstract_type();
4149
4150       if (type->is_void_type())
4151         type = Type::make_error_type();
4152     }
4153
4154   this->seen_ = false;
4155
4156   return type;
4157 }
4158
4159 // Fetch the type from a const pointer, in which case it should have
4160 // been set already.