OSDN Git Service

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