OSDN Git Service

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