OSDN Git Service

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