OSDN Git Service

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