OSDN Git Service

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