OSDN Git Service

8f0d3288694dd26e6635bb5bc87b4f77a8915aaf
[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                                                     p->location());
2664       Named_object* no = block->bindings()->add_result_variable(name, result);
2665       if (no->is_result_variable())
2666         this->results_->push_back(no);
2667       else
2668         {
2669           static int dummy_result_count;
2670           char buf[100];
2671           snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2672           ++dummy_result_count;
2673           name = gogo->pack_hidden_name(buf, false);
2674           no = block->bindings()->add_result_variable(name, result);
2675           gcc_assert(no->is_result_variable());
2676           this->results_->push_back(no);
2677         }
2678     }
2679 }
2680
2681 // Update the named result variables when cloning a function which
2682 // calls recover.
2683
2684 void
2685 Function::update_result_variables()
2686 {
2687   if (this->results_ == NULL)
2688     return;
2689
2690   for (Results::iterator p = this->results_->begin();
2691        p != this->results_->end();
2692        ++p)
2693     (*p)->result_var_value()->set_function(this);
2694 }
2695
2696 // Return the closure variable, creating it if necessary.
2697
2698 Named_object*
2699 Function::closure_var()
2700 {
2701   if (this->closure_var_ == NULL)
2702     {
2703       // We don't know the type of the variable yet.  We add fields as
2704       // we find them.
2705       source_location loc = this->type_->location();
2706       Struct_field_list* sfl = new Struct_field_list;
2707       Type* struct_type = Type::make_struct_type(sfl, loc);
2708       Variable* var = new Variable(Type::make_pointer_type(struct_type),
2709                                    NULL, false, true, false, loc);
2710       this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2711       // Note that the new variable is not in any binding contour.
2712     }
2713   return this->closure_var_;
2714 }
2715
2716 // Set the type of the closure variable.
2717
2718 void
2719 Function::set_closure_type()
2720 {
2721   if (this->closure_var_ == NULL)
2722     return;
2723   Named_object* closure = this->closure_var_;
2724   Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2725   unsigned int index = 0;
2726   for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2727        p != this->closure_fields_.end();
2728        ++p, ++index)
2729     {
2730       Named_object* no = p->first;
2731       char buf[20];
2732       snprintf(buf, sizeof buf, "%u", index);
2733       std::string n = no->name() + buf;
2734       Type* var_type;
2735       if (no->is_variable())
2736         var_type = no->var_value()->type();
2737       else
2738         var_type = no->result_var_value()->type();
2739       Type* field_type = Type::make_pointer_type(var_type);
2740       st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2741     }
2742 }
2743
2744 // Return whether this function is a method.
2745
2746 bool
2747 Function::is_method() const
2748 {
2749   return this->type_->is_method();
2750 }
2751
2752 // Add a label definition.
2753
2754 Label*
2755 Function::add_label_definition(const std::string& label_name,
2756                                source_location location)
2757 {
2758   Label* lnull = NULL;
2759   std::pair<Labels::iterator, bool> ins =
2760     this->labels_.insert(std::make_pair(label_name, lnull));
2761   if (ins.second)
2762     {
2763       // This is a new label.
2764       Label* label = new Label(label_name);
2765       label->define(location);
2766       ins.first->second = label;
2767       return label;
2768     }
2769   else
2770     {
2771       // The label was already in the hash table.
2772       Label* label = ins.first->second;
2773       if (!label->is_defined())
2774         {
2775           label->define(location);
2776           return label;
2777         }
2778       else
2779         {
2780           error_at(location, "label %qs already defined",
2781                    Gogo::message_name(label_name).c_str());
2782           inform(label->location(), "previous definition of %qs was here",
2783                  Gogo::message_name(label_name).c_str());
2784           return new Label(label_name);
2785         }
2786     }
2787 }
2788
2789 // Add a reference to a label.
2790
2791 Label*
2792 Function::add_label_reference(const std::string& label_name)
2793 {
2794   Label* lnull = NULL;
2795   std::pair<Labels::iterator, bool> ins =
2796     this->labels_.insert(std::make_pair(label_name, lnull));
2797   if (!ins.second)
2798     {
2799       // The label was already in the hash table.
2800       Label* label = ins.first->second;
2801       label->set_is_used();
2802       return label;
2803     }
2804   else
2805     {
2806       gcc_assert(ins.first->second == NULL);
2807       Label* label = new Label(label_name);
2808       ins.first->second = label;
2809       label->set_is_used();
2810       return label;
2811     }
2812 }
2813
2814 // Warn about labels that are defined but not used.
2815
2816 void
2817 Function::check_labels() const
2818 {
2819   for (Labels::const_iterator p = this->labels_.begin();
2820        p != this->labels_.end();
2821        p++)
2822     {
2823       Label* label = p->second;
2824       if (!label->is_used())
2825         error_at(label->location(), "label %qs defined and not used",
2826                  Gogo::message_name(label->name()).c_str());
2827     }
2828 }
2829
2830 // Swap one function with another.  This is used when building the
2831 // thunk we use to call a function which calls recover.  It may not
2832 // work for any other case.
2833
2834 void
2835 Function::swap_for_recover(Function *x)
2836 {
2837   gcc_assert(this->enclosing_ == x->enclosing_);
2838   std::swap(this->results_, x->results_);
2839   std::swap(this->closure_var_, x->closure_var_);
2840   std::swap(this->block_, x->block_);
2841   gcc_assert(this->location_ == x->location_);
2842   gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2843   gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2844 }
2845
2846 // Traverse the tree.
2847
2848 int
2849 Function::traverse(Traverse* traverse)
2850 {
2851   unsigned int traverse_mask = traverse->traverse_mask();
2852
2853   if ((traverse_mask
2854        & (Traverse::traverse_types | Traverse::traverse_expressions))
2855       != 0)
2856     {
2857       if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2858         return TRAVERSE_EXIT;
2859     }
2860
2861   // FIXME: We should check traverse_functions here if nested
2862   // functions are stored in block bindings.
2863   if (this->block_ != NULL
2864       && (traverse_mask
2865           & (Traverse::traverse_variables
2866              | Traverse::traverse_constants
2867              | Traverse::traverse_blocks
2868              | Traverse::traverse_statements
2869              | Traverse::traverse_expressions
2870              | Traverse::traverse_types)) != 0)
2871     {
2872       if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2873         return TRAVERSE_EXIT;
2874     }
2875
2876   return TRAVERSE_CONTINUE;
2877 }
2878
2879 // Work out types for unspecified variables and constants.
2880
2881 void
2882 Function::determine_types()
2883 {
2884   if (this->block_ != NULL)
2885     this->block_->determine_types();
2886 }
2887
2888 // Get a pointer to the variable holding the defer stack for this
2889 // function, making it if necessary.  At least at present, the value
2890 // of this variable is not used.  However, a pointer to this variable
2891 // is used as a marker for the functions on the defer stack associated
2892 // with this function.  Doing things this way permits inlining a
2893 // function which uses defer.
2894
2895 Expression*
2896 Function::defer_stack(source_location location)
2897 {
2898   Type* t = Type::make_pointer_type(Type::make_void_type());
2899   if (this->defer_stack_ == NULL)
2900     {
2901       Expression* n = Expression::make_nil(location);
2902       this->defer_stack_ = Statement::make_temporary(t, n, location);
2903       this->defer_stack_->set_is_address_taken();
2904     }
2905   Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
2906                                                          location);
2907   Expression* addr = Expression::make_unary(OPERATOR_AND, ref, location);
2908   return Expression::make_unsafe_cast(t, addr, location);
2909 }
2910
2911 // Export the function.
2912
2913 void
2914 Function::export_func(Export* exp, const std::string& name) const
2915 {
2916   Function::export_func_with_type(exp, name, this->type_);
2917 }
2918
2919 // Export a function with a type.
2920
2921 void
2922 Function::export_func_with_type(Export* exp, const std::string& name,
2923                                 const Function_type* fntype)
2924 {
2925   exp->write_c_string("func ");
2926
2927   if (fntype->is_method())
2928     {
2929       exp->write_c_string("(");
2930       exp->write_type(fntype->receiver()->type());
2931       exp->write_c_string(") ");
2932     }
2933
2934   exp->write_string(name);
2935
2936   exp->write_c_string(" (");
2937   const Typed_identifier_list* parameters = fntype->parameters();
2938   if (parameters != NULL)
2939     {
2940       bool is_varargs = fntype->is_varargs();
2941       bool first = true;
2942       for (Typed_identifier_list::const_iterator p = parameters->begin();
2943            p != parameters->end();
2944            ++p)
2945         {
2946           if (first)
2947             first = false;
2948           else
2949             exp->write_c_string(", ");
2950           if (!is_varargs || p + 1 != parameters->end())
2951             exp->write_type(p->type());
2952           else
2953             {
2954               exp->write_c_string("...");
2955               exp->write_type(p->type()->array_type()->element_type());
2956             }
2957         }
2958     }
2959   exp->write_c_string(")");
2960
2961   const Typed_identifier_list* results = fntype->results();
2962   if (results != NULL)
2963     {
2964       if (results->size() == 1)
2965         {
2966           exp->write_c_string(" ");
2967           exp->write_type(results->begin()->type());
2968         }
2969       else
2970         {
2971           exp->write_c_string(" (");
2972           bool first = true;
2973           for (Typed_identifier_list::const_iterator p = results->begin();
2974                p != results->end();
2975                ++p)
2976             {
2977               if (first)
2978                 first = false;
2979               else
2980                 exp->write_c_string(", ");
2981               exp->write_type(p->type());
2982             }
2983           exp->write_c_string(")");
2984         }
2985     }
2986   exp->write_c_string(";\n");
2987 }
2988
2989 // Import a function.
2990
2991 void
2992 Function::import_func(Import* imp, std::string* pname,
2993                       Typed_identifier** preceiver,
2994                       Typed_identifier_list** pparameters,
2995                       Typed_identifier_list** presults,
2996                       bool* is_varargs)
2997 {
2998   imp->require_c_string("func ");
2999
3000   *preceiver = NULL;
3001   if (imp->peek_char() == '(')
3002     {
3003       imp->require_c_string("(");
3004       Type* rtype = imp->read_type();
3005       *preceiver = new Typed_identifier(Import::import_marker, rtype,
3006                                         imp->location());
3007       imp->require_c_string(") ");
3008     }
3009
3010   *pname = imp->read_identifier();
3011
3012   Typed_identifier_list* parameters;
3013   *is_varargs = false;
3014   imp->require_c_string(" (");
3015   if (imp->peek_char() == ')')
3016     parameters = NULL;
3017   else
3018     {
3019       parameters = new Typed_identifier_list();
3020       while (true)
3021         {
3022           if (imp->match_c_string("..."))
3023             {
3024               imp->advance(3);
3025               *is_varargs = true;
3026             }
3027
3028           Type* ptype = imp->read_type();
3029           if (*is_varargs)
3030             ptype = Type::make_array_type(ptype, NULL);
3031           parameters->push_back(Typed_identifier(Import::import_marker,
3032                                                  ptype, imp->location()));
3033           if (imp->peek_char() != ',')
3034             break;
3035           gcc_assert(!*is_varargs);
3036           imp->require_c_string(", ");
3037         }
3038     }
3039   imp->require_c_string(")");
3040   *pparameters = parameters;
3041
3042   Typed_identifier_list* results;
3043   if (imp->peek_char() != ' ')
3044     results = NULL;
3045   else
3046     {
3047       results = new Typed_identifier_list();
3048       imp->require_c_string(" ");
3049       if (imp->peek_char() != '(')
3050         {
3051           Type* rtype = imp->read_type();
3052           results->push_back(Typed_identifier(Import::import_marker, rtype,
3053                                               imp->location()));
3054         }
3055       else
3056         {
3057           imp->require_c_string("(");
3058           while (true)
3059             {
3060               Type* rtype = imp->read_type();
3061               results->push_back(Typed_identifier(Import::import_marker,
3062                                                   rtype, imp->location()));
3063               if (imp->peek_char() != ',')
3064                 break;
3065               imp->require_c_string(", ");
3066             }
3067           imp->require_c_string(")");
3068         }
3069     }
3070   imp->require_c_string(";\n");
3071   *presults = results;
3072 }
3073
3074 // Class Block.
3075
3076 Block::Block(Block* enclosing, source_location location)
3077   : enclosing_(enclosing), statements_(),
3078     bindings_(new Bindings(enclosing == NULL
3079                            ? NULL
3080                            : enclosing->bindings())),
3081     start_location_(location),
3082     end_location_(UNKNOWN_LOCATION)
3083 {
3084 }
3085
3086 // Add a statement to a block.
3087
3088 void
3089 Block::add_statement(Statement* statement)
3090 {
3091   this->statements_.push_back(statement);
3092 }
3093
3094 // Add a statement to the front of a block.  This is slow but is only
3095 // used for reference counts of parameters.
3096
3097 void
3098 Block::add_statement_at_front(Statement* statement)
3099 {
3100   this->statements_.insert(this->statements_.begin(), statement);
3101 }
3102
3103 // Replace a statement in a block.
3104
3105 void
3106 Block::replace_statement(size_t index, Statement* s)
3107 {
3108   gcc_assert(index < this->statements_.size());
3109   this->statements_[index] = s;
3110 }
3111
3112 // Add a statement before another statement.
3113
3114 void
3115 Block::insert_statement_before(size_t index, Statement* s)
3116 {
3117   gcc_assert(index < this->statements_.size());
3118   this->statements_.insert(this->statements_.begin() + index, s);
3119 }
3120
3121 // Add a statement after another statement.
3122
3123 void
3124 Block::insert_statement_after(size_t index, Statement* s)
3125 {
3126   gcc_assert(index < this->statements_.size());
3127   this->statements_.insert(this->statements_.begin() + index + 1, s);
3128 }
3129
3130 // Traverse the tree.
3131
3132 int
3133 Block::traverse(Traverse* traverse)
3134 {
3135   unsigned int traverse_mask = traverse->traverse_mask();
3136
3137   if ((traverse_mask & Traverse::traverse_blocks) != 0)
3138     {
3139       int t = traverse->block(this);
3140       if (t == TRAVERSE_EXIT)
3141         return TRAVERSE_EXIT;
3142       else if (t == TRAVERSE_SKIP_COMPONENTS)
3143         return TRAVERSE_CONTINUE;
3144     }
3145
3146   if ((traverse_mask
3147        & (Traverse::traverse_variables
3148           | Traverse::traverse_constants
3149           | Traverse::traverse_expressions
3150           | Traverse::traverse_types)) != 0)
3151     {
3152       for (Bindings::const_definitions_iterator pb =
3153              this->bindings_->begin_definitions();
3154            pb != this->bindings_->end_definitions();
3155            ++pb)
3156         {
3157           switch ((*pb)->classification())
3158             {
3159             case Named_object::NAMED_OBJECT_CONST:
3160               if ((traverse_mask & Traverse::traverse_constants) != 0)
3161                 {
3162                   if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
3163                     return TRAVERSE_EXIT;
3164                 }
3165               if ((traverse_mask & Traverse::traverse_types) != 0
3166                   || (traverse_mask & Traverse::traverse_expressions) != 0)
3167                 {
3168                   Type* t = (*pb)->const_value()->type();
3169                   if (t != NULL
3170                       && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3171                     return TRAVERSE_EXIT;
3172                 }
3173               if ((traverse_mask & Traverse::traverse_expressions) != 0
3174                   || (traverse_mask & Traverse::traverse_types) != 0)
3175                 {
3176                   if ((*pb)->const_value()->traverse_expression(traverse)
3177                       == TRAVERSE_EXIT)
3178                     return TRAVERSE_EXIT;
3179                 }
3180               break;
3181
3182             case Named_object::NAMED_OBJECT_VAR:
3183             case Named_object::NAMED_OBJECT_RESULT_VAR:
3184               if ((traverse_mask & Traverse::traverse_variables) != 0)
3185                 {
3186                   if (traverse->variable(*pb) == TRAVERSE_EXIT)
3187                     return TRAVERSE_EXIT;
3188                 }
3189               if (((traverse_mask & Traverse::traverse_types) != 0
3190                    || (traverse_mask & Traverse::traverse_expressions) != 0)
3191                   && ((*pb)->is_result_variable()
3192                       || (*pb)->var_value()->has_type()))
3193                 {
3194                   Type* t = ((*pb)->is_variable()
3195                              ? (*pb)->var_value()->type()
3196                              : (*pb)->result_var_value()->type());
3197                   if (t != NULL
3198                       && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3199                     return TRAVERSE_EXIT;
3200                 }
3201               if ((*pb)->is_variable()
3202                   && ((traverse_mask & Traverse::traverse_expressions) != 0
3203                       || (traverse_mask & Traverse::traverse_types) != 0))
3204                 {
3205                   if ((*pb)->var_value()->traverse_expression(traverse)
3206                       == TRAVERSE_EXIT)
3207                     return TRAVERSE_EXIT;
3208                 }
3209               break;
3210
3211             case Named_object::NAMED_OBJECT_FUNC:
3212             case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3213               // FIXME: Where will nested functions be found?
3214               gcc_unreachable();
3215
3216             case Named_object::NAMED_OBJECT_TYPE:
3217               if ((traverse_mask & Traverse::traverse_types) != 0
3218                   || (traverse_mask & Traverse::traverse_expressions) != 0)
3219                 {
3220                   if (Type::traverse((*pb)->type_value(), traverse)
3221                       == TRAVERSE_EXIT)
3222                     return TRAVERSE_EXIT;
3223                 }
3224               break;
3225
3226             case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3227             case Named_object::NAMED_OBJECT_UNKNOWN:
3228               break;
3229
3230             case Named_object::NAMED_OBJECT_PACKAGE:
3231             case Named_object::NAMED_OBJECT_SINK:
3232               gcc_unreachable();
3233
3234             default:
3235               gcc_unreachable();
3236             }
3237         }
3238     }
3239
3240   // No point in checking traverse_mask here--if we got here we always
3241   // want to walk the statements.  The traversal can insert new
3242   // statements before or after the current statement.  Inserting
3243   // statements before the current statement requires updating I via
3244   // the pointer; those statements will not be traversed.  Any new
3245   // statements inserted after the current statement will be traversed
3246   // in their turn.
3247   for (size_t i = 0; i < this->statements_.size(); ++i)
3248     {
3249       if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3250         return TRAVERSE_EXIT;
3251     }
3252
3253   return TRAVERSE_CONTINUE;
3254 }
3255
3256 // Work out types for unspecified variables and constants.
3257
3258 void
3259 Block::determine_types()
3260 {
3261   for (Bindings::const_definitions_iterator pb =
3262          this->bindings_->begin_definitions();
3263        pb != this->bindings_->end_definitions();
3264        ++pb)
3265     {
3266       if ((*pb)->is_variable())
3267         (*pb)->var_value()->determine_type();
3268       else if ((*pb)->is_const())
3269         (*pb)->const_value()->determine_type();
3270     }
3271
3272   for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3273        ps != this->statements_.end();
3274        ++ps)
3275     (*ps)->determine_types();
3276 }
3277
3278 // Return true if the statements in this block may fall through.
3279
3280 bool
3281 Block::may_fall_through() const
3282 {
3283   if (this->statements_.empty())
3284     return true;
3285   return this->statements_.back()->may_fall_through();
3286 }
3287
3288 // Class Variable.
3289
3290 Variable::Variable(Type* type, Expression* init, bool is_global,
3291                    bool is_parameter, bool is_receiver,
3292                    source_location location)
3293   : type_(type), init_(init), preinit_(NULL), location_(location),
3294     backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3295     is_receiver_(is_receiver), is_varargs_parameter_(false),
3296     is_address_taken_(false), seen_(false), init_is_lowered_(false),
3297     type_from_init_tuple_(false), type_from_range_index_(false),
3298     type_from_range_value_(false), type_from_chan_element_(false),
3299     is_type_switch_var_(false), determined_type_(false)
3300 {
3301   gcc_assert(type != NULL || init != NULL);
3302   gcc_assert(!is_parameter || init == NULL);
3303 }
3304
3305 // Traverse the initializer expression.
3306
3307 int
3308 Variable::traverse_expression(Traverse* traverse)
3309 {
3310   if (this->preinit_ != NULL)
3311     {
3312       if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3313         return TRAVERSE_EXIT;
3314     }
3315   if (this->init_ != NULL)
3316     {
3317       if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3318         return TRAVERSE_EXIT;
3319     }
3320   return TRAVERSE_CONTINUE;
3321 }
3322
3323 // Lower the initialization expression after parsing is complete.
3324
3325 void
3326 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3327 {
3328   if (this->init_ != NULL && !this->init_is_lowered_)
3329     {
3330       if (this->seen_)
3331         {
3332           // We will give an error elsewhere, this is just to prevent
3333           // an infinite loop.
3334           return;
3335         }
3336       this->seen_ = true;
3337
3338       gogo->lower_expression(function, &this->init_);
3339
3340       this->seen_ = false;
3341
3342       this->init_is_lowered_ = true;
3343     }
3344 }
3345
3346 // Get the preinit block.
3347
3348 Block*
3349 Variable::preinit_block(Gogo* gogo)
3350 {
3351   gcc_assert(this->is_global_);
3352   if (this->preinit_ == NULL)
3353     this->preinit_ = new Block(NULL, this->location());
3354
3355   // If a global variable has a preinitialization statement, then we
3356   // need to have an initialization function.
3357   gogo->set_need_init_fn();
3358
3359   return this->preinit_;
3360 }
3361
3362 // Add a statement to be run before the initialization expression.
3363
3364 void
3365 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3366 {
3367   Block* b = this->preinit_block(gogo);
3368   b->add_statement(s);
3369   b->set_end_location(s->location());
3370 }
3371
3372 // In an assignment which sets a variable to a tuple of EXPR, return
3373 // the type of the first element of the tuple.
3374
3375 Type*
3376 Variable::type_from_tuple(Expression* expr, bool report_error) const
3377 {
3378   if (expr->map_index_expression() != NULL)
3379     {
3380       Map_type* mt = expr->map_index_expression()->get_map_type();
3381       if (mt == NULL)
3382         return Type::make_error_type();
3383       return mt->val_type();
3384     }
3385   else if (expr->receive_expression() != NULL)
3386     {
3387       Expression* channel = expr->receive_expression()->channel();
3388       Type* channel_type = channel->type();
3389       if (channel_type->channel_type() == NULL)
3390         return Type::make_error_type();
3391       return channel_type->channel_type()->element_type();
3392     }
3393   else
3394     {
3395       if (report_error)
3396         error_at(this->location(), "invalid tuple definition");
3397       return Type::make_error_type();
3398     }
3399 }
3400
3401 // Given EXPR used in a range clause, return either the index type or
3402 // the value type of the range, depending upon GET_INDEX_TYPE.
3403
3404 Type*
3405 Variable::type_from_range(Expression* expr, bool get_index_type,
3406                           bool report_error) const
3407 {
3408   Type* t = expr->type();
3409   if (t->array_type() != NULL
3410       || (t->points_to() != NULL
3411           && t->points_to()->array_type() != NULL
3412           && !t->points_to()->is_open_array_type()))
3413     {
3414       if (get_index_type)
3415         return Type::lookup_integer_type("int");
3416       else
3417         return t->deref()->array_type()->element_type();
3418     }
3419   else if (t->is_string_type())
3420     return Type::lookup_integer_type("int");
3421   else if (t->map_type() != NULL)
3422     {
3423       if (get_index_type)
3424         return t->map_type()->key_type();
3425       else
3426         return t->map_type()->val_type();
3427     }
3428   else if (t->channel_type() != NULL)
3429     {
3430       if (get_index_type)
3431         return t->channel_type()->element_type();
3432       else
3433         {
3434           if (report_error)
3435             error_at(this->location(),
3436                      "invalid definition of value variable for channel range");
3437           return Type::make_error_type();
3438         }
3439     }
3440   else
3441     {
3442       if (report_error)
3443         error_at(this->location(), "invalid type for range clause");
3444       return Type::make_error_type();
3445     }
3446 }
3447
3448 // EXPR should be a channel.  Return the channel's element type.
3449
3450 Type*
3451 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3452 {
3453   Type* t = expr->type();
3454   if (t->channel_type() != NULL)
3455     return t->channel_type()->element_type();
3456   else
3457     {
3458       if (report_error)
3459         error_at(this->location(), "expected channel");
3460       return Type::make_error_type();
3461     }
3462 }
3463
3464 // Return the type of the Variable.  This may be called before
3465 // Variable::determine_type is called, which means that we may need to
3466 // get the type from the initializer.  FIXME: If we combine lowering
3467 // with type determination, then this should be unnecessary.
3468
3469 Type*
3470 Variable::type()
3471 {
3472   // A variable in a type switch with a nil case will have the wrong
3473   // type here.  This gets fixed up in determine_type, below.
3474   Type* type = this->type_;
3475   Expression* init = this->init_;
3476   if (this->is_type_switch_var_
3477       && this->type_->is_nil_constant_as_type())
3478     {
3479       Type_guard_expression* tge = this->init_->type_guard_expression();
3480       gcc_assert(tge != NULL);
3481       init = tge->expr();
3482       type = NULL;
3483     }
3484
3485   if (this->seen_)
3486     {
3487       if (this->type_ == NULL || !this->type_->is_error_type())
3488         {
3489           error_at(this->location_, "variable initializer refers to itself");
3490           this->type_ = Type::make_error_type();
3491         }
3492       return this->type_;
3493     }
3494
3495   this->seen_ = true;
3496
3497   if (type != NULL)
3498     ;
3499   else if (this->type_from_init_tuple_)
3500     type = this->type_from_tuple(init, false);
3501   else if (this->type_from_range_index_ || this->type_from_range_value_)
3502     type = this->type_from_range(init, this->type_from_range_index_, false);
3503   else if (this->type_from_chan_element_)
3504     type = this->type_from_chan_element(init, false);
3505   else
3506     {
3507       gcc_assert(init != NULL);
3508       type = init->type();
3509       gcc_assert(type != NULL);
3510
3511       // Variables should not have abstract types.
3512       if (type->is_abstract())
3513         type = type->make_non_abstract_type();
3514
3515       if (type->is_void_type())
3516         type = Type::make_error_type();
3517     }
3518
3519   this->seen_ = false;
3520
3521   return type;
3522 }
3523
3524 // Fetch the type from a const pointer, in which case it should have
3525 // been set already.
3526
3527 Type*
3528 Variable::type() const
3529 {
3530   gcc_assert(this->type_ != NULL);
3531   return this->type_;
3532 }
3533
3534 // Set the type if necessary.
3535
3536 void
3537 Variable::determine_type()
3538 {
3539   if (this->determined_type_)
3540     return;
3541   this->determined_type_ = true;
3542
3543   if (this->preinit_ != NULL)
3544     this->preinit_->determine_types();
3545
3546   // A variable in a type switch with a nil case will have the wrong
3547   // type here.  It will have an initializer which is a type guard.
3548   // We want to initialize it to the value without the type guard, and
3549   // use the type of that value as well.
3550   if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3551     {
3552       Type_guard_expression* tge = this->init_->type_guard_expression();
3553       gcc_assert(tge != NULL);
3554       this->type_ = NULL;
3555       this->init_ = tge->expr();
3556     }
3557
3558   if (this->init_ == NULL)
3559     gcc_assert(this->type_ != NULL && !this->type_->is_abstract());
3560   else if (this->type_from_init_tuple_)
3561     {
3562       Expression *init = this->init_;
3563       init->determine_type_no_context();
3564       this->type_ = this->type_from_tuple(init, true);
3565       this->init_ = NULL;
3566     }
3567   else if (this->type_from_range_index_ || this->type_from_range_value_)
3568     {
3569       Expression* init = this->init_;
3570       init->determine_type_no_context();
3571       this->type_ = this->type_from_range(init, this->type_from_range_index_,
3572                                           true);
3573       this->init_ = NULL;
3574     }
3575   else if (this->type_from_chan_element_)
3576     {
3577       Expression* init = this->init_;
3578       init->determine_type_no_context();
3579       this->type_ = this->type_from_chan_element(init, true);
3580       this->init_ = NULL;
3581     }
3582   else
3583     {
3584       Type_context context(this->type_, false);
3585       this->init_->determine_type(&context);
3586       if (this->type_ == NULL)
3587         {
3588           Type* type = this->init_->type();
3589           gcc_assert(type != NULL);
3590           if (type->is_abstract())
3591             type = type->make_non_abstract_type();
3592
3593           if (type->is_void_type())
3594             {
3595               error_at(this->location_, "variable has no type");
3596               type = Type::make_error_type();
3597             }
3598           else if (type->is_nil_type())
3599             {
3600               error_at(this->location_, "variable defined to nil type");
3601               type = Type::make_error_type();
3602             }
3603           else if (type->is_call_multiple_result_type())
3604             {
3605               error_at(this->location_,
3606                        "single variable set to multiple value function call");
3607               type = Type::make_error_type();
3608             }
3609
3610           this->type_ = type;
3611         }
3612     }
3613 }
3614
3615 // Export the variable
3616
3617 void
3618 Variable::export_var(Export* exp, const std::string& name) const
3619 {
3620   gcc_assert(this->is_global_);
3621   exp->write_c_string("var ");
3622   exp->write_string(name);
3623   exp->write_c_string(" ");
3624   exp->write_type(this->type());
3625   exp->write_c_string(";\n");
3626 }
3627
3628 // Import a variable.
3629
3630 void
3631 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3632 {
3633   imp->require_c_string("var ");
3634   *pname = imp->read_identifier();
3635   imp->require_c_string(" ");
3636   *ptype = imp->read_type();
3637   imp->require_c_string(";\n");
3638 }
3639
3640 // Convert a variable to the backend representation.
3641
3642 Bvariable*
3643 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
3644                                const Package* package, const std::string& name)
3645 {
3646   if (this->backend_ == NULL)
3647     {
3648       Backend* backend = gogo->backend();
3649       Type* type = this->type_;
3650       if (type->is_error_type()
3651           || (type->is_undefined()
3652               && (!this->is_global_ || package == NULL)))
3653         this->backend_ = backend->error_variable();
3654       else
3655         {
3656           bool is_parameter = this->is_parameter_;
3657           if (this->is_receiver_ && type->points_to() == NULL)
3658             is_parameter = false;
3659           if (this->is_in_heap())
3660             {
3661               is_parameter = false;
3662               type = Type::make_pointer_type(type);
3663             }
3664
3665           std::string n = Gogo::unpack_hidden_name(name);
3666           Btype* btype = tree_to_type(type->get_tree(gogo));
3667
3668           Bvariable* bvar;
3669           if (this->is_global_)
3670             bvar = backend->global_variable((package == NULL
3671                                              ? gogo->package_name()
3672                                              : package->name()),
3673                                             (package == NULL
3674                                              ? gogo->unique_prefix()
3675                                              : package->unique_prefix()),
3676                                             n,
3677                                             btype,
3678                                             package != NULL,
3679                                             Gogo::is_hidden_name(name),
3680                                             this->location_);
3681           else
3682             {
3683               tree fndecl = function->func_value()->get_decl();
3684               Bfunction* bfunction = tree_to_function(fndecl);
3685               if (is_parameter)
3686                 bvar = backend->parameter_variable(bfunction, n, btype,
3687                                                    this->location_);
3688               else
3689                 bvar = backend->local_variable(bfunction, n, btype,
3690                                                this->location_);
3691             }
3692           this->backend_ = bvar;
3693         }
3694     }
3695   return this->backend_;
3696 }
3697
3698 // Class Result_variable.
3699
3700 // Convert a result variable to the backend representation.
3701
3702 Bvariable*
3703 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
3704                                       const std::string& name)
3705 {
3706   if (this->backend_ == NULL)
3707     {
3708       Backend* backend = gogo->backend();
3709       Type* type = this->type_;
3710       if (type->is_error())
3711         this->backend_ = backend->error_variable();
3712       else
3713         {
3714           if (this->is_in_heap())
3715             type = Type::make_pointer_type(type);
3716           Btype* btype = tree_to_type(type->get_tree(gogo));
3717           tree fndecl = function->func_value()->get_decl();
3718           Bfunction* bfunction = tree_to_function(fndecl);
3719           std::string n = Gogo::unpack_hidden_name(name);
3720           this->backend_ = backend->local_variable(bfunction, n, btype,
3721                                                    this->location_);
3722         }
3723     }
3724   return this->backend_;
3725 }
3726
3727 // Class Named_constant.
3728
3729 // Traverse the initializer expression.
3730
3731 int
3732 Named_constant::traverse_expression(Traverse* traverse)
3733 {
3734   return Expression::traverse(&this->expr_, traverse);
3735 }
3736
3737 // Determine the type of the constant.
3738
3739 void
3740 Named_constant::determine_type()
3741 {
3742   if (this->type_ != NULL)
3743     {
3744       Type_context context(this->type_, false);
3745       this->expr_->determine_type(&context);
3746     }
3747   else
3748     {
3749       // A constant may have an abstract type.
3750       Type_context context(NULL, true);
3751       this->expr_->determine_type(&context);
3752       this->type_ = this->expr_->type();
3753       gcc_assert(this->type_ != NULL);
3754     }
3755 }
3756
3757 // Indicate that we found and reported an error for this constant.
3758
3759 void
3760 Named_constant::set_error()
3761 {
3762   this->type_ = Type::make_error_type();
3763   this->expr_ = Expression::make_error(this->location_);
3764 }
3765
3766 // Export a constant.
3767
3768 void
3769 Named_constant::export_const(Export* exp, const std::string& name) const
3770 {
3771   exp->write_c_string("const ");
3772   exp->write_string(name);
3773   exp->write_c_string(" ");
3774   if (!this->type_->is_abstract())
3775     {
3776       exp->write_type(this->type_);
3777       exp->write_c_string(" ");
3778     }
3779   exp->write_c_string("= ");
3780   this->expr()->export_expression(exp);
3781   exp->write_c_string(";\n");
3782 }
3783
3784 // Import a constant.
3785
3786 void
3787 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3788                              Expression** pexpr)
3789 {
3790   imp->require_c_string("const ");
3791   *pname = imp->read_identifier();
3792   imp->require_c_string(" ");
3793   if (imp->peek_char() == '=')
3794     *ptype = NULL;
3795   else
3796     {
3797       *ptype = imp->read_type();
3798       imp->require_c_string(" ");
3799     }
3800   imp->require_c_string("= ");
3801   *pexpr = Expression::import_expression(imp);
3802   imp->require_c_string(";\n");
3803 }
3804
3805 // Add a method.
3806
3807 Named_object*
3808 Type_declaration::add_method(const std::string& name, Function* function)
3809 {
3810   Named_object* ret = Named_object::make_function(name, NULL, function);
3811   this->methods_.push_back(ret);
3812   return ret;
3813 }
3814
3815 // Add a method declaration.
3816
3817 Named_object*
3818 Type_declaration::add_method_declaration(const std::string&  name,
3819                                          Function_type* type,
3820                                          source_location location)
3821 {
3822   Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3823                                                               location);
3824   this->methods_.push_back(ret);
3825   return ret;
3826 }
3827
3828 // Return whether any methods ere defined.
3829
3830 bool
3831 Type_declaration::has_methods() const
3832 {
3833   return !this->methods_.empty();
3834 }
3835
3836 // Define methods for the real type.
3837
3838 void
3839 Type_declaration::define_methods(Named_type* nt)
3840 {
3841   for (Methods::const_iterator p = this->methods_.begin();
3842        p != this->methods_.end();
3843        ++p)
3844     nt->add_existing_method(*p);
3845 }
3846
3847 // We are using the type.  Return true if we should issue a warning.
3848
3849 bool
3850 Type_declaration::using_type()
3851 {
3852   bool ret = !this->issued_warning_;
3853   this->issued_warning_ = true;
3854   return ret;
3855 }
3856
3857 // Class Unknown_name.
3858
3859 // Set the real named object.
3860
3861 void
3862 Unknown_name::set_real_named_object(Named_object* no)
3863 {
3864   gcc_assert(this->real_named_object_ == NULL);
3865   gcc_assert(!no->is_unknown());
3866   this->real_named_object_ = no;
3867 }
3868
3869 // Class Named_object.
3870
3871 Named_object::Named_object(const std::string& name,
3872                            const Package* package,
3873                            Classification classification)
3874   : name_(name), package_(package), classification_(classification),
3875     tree_(NULL)
3876 {
3877   if (Gogo::is_sink_name(name))
3878     gcc_assert(classification == NAMED_OBJECT_SINK);
3879 }
3880
3881 // Make an unknown name.  This is used by the parser.  The name must
3882 // be resolved later.  Unknown names are only added in the current
3883 // package.
3884
3885 Named_object*
3886 Named_object::make_unknown_name(const std::string& name,
3887                                 source_location location)
3888 {
3889   Named_object* named_object = new Named_object(name, NULL,
3890                                                 NAMED_OBJECT_UNKNOWN);
3891   Unknown_name* value = new Unknown_name(location);
3892   named_object->u_.unknown_value = value;
3893   return named_object;
3894 }
3895
3896 // Make a constant.
3897
3898 Named_object*
3899 Named_object::make_constant(const Typed_identifier& tid,
3900                             const Package* package, Expression* expr,
3901                             int iota_value)
3902 {
3903   Named_object* named_object = new Named_object(tid.name(), package,
3904                                                 NAMED_OBJECT_CONST);
3905   Named_constant* named_constant = new Named_constant(tid.type(), expr,
3906                                                       iota_value,
3907                                                       tid.location());
3908   named_object->u_.const_value = named_constant;
3909   return named_object;
3910 }
3911
3912 // Make a named type.
3913
3914 Named_object*
3915 Named_object::make_type(const std::string& name, const Package* package,
3916                         Type* type, source_location location)
3917 {
3918   Named_object* named_object = new Named_object(name, package,
3919                                                 NAMED_OBJECT_TYPE);
3920   Named_type* named_type = Type::make_named_type(named_object, type, location);
3921   named_object->u_.type_value = named_type;
3922   return named_object;
3923 }
3924
3925 // Make a type declaration.
3926
3927 Named_object*
3928 Named_object::make_type_declaration(const std::string& name,
3929                                     const Package* package,
3930                                     source_location location)
3931 {
3932   Named_object* named_object = new Named_object(name, package,
3933                                                 NAMED_OBJECT_TYPE_DECLARATION);
3934   Type_declaration* type_declaration = new Type_declaration(location);
3935   named_object->u_.type_declaration = type_declaration;
3936   return named_object;
3937 }
3938
3939 // Make a variable.
3940
3941 Named_object*
3942 Named_object::make_variable(const std::string& name, const Package* package,
3943                             Variable* variable)
3944 {
3945   Named_object* named_object = new Named_object(name, package,
3946                                                 NAMED_OBJECT_VAR);
3947   named_object->u_.var_value = variable;
3948   return named_object;
3949 }
3950
3951 // Make a result variable.
3952
3953 Named_object*
3954 Named_object::make_result_variable(const std::string& name,
3955                                    Result_variable* result)
3956 {
3957   Named_object* named_object = new Named_object(name, NULL,
3958                                                 NAMED_OBJECT_RESULT_VAR);
3959   named_object->u_.result_var_value = result;
3960   return named_object;
3961 }
3962
3963 // Make a sink.  This is used for the special blank identifier _.
3964
3965 Named_object*
3966 Named_object::make_sink()
3967 {
3968   return new Named_object("_", NULL, NAMED_OBJECT_SINK);
3969 }
3970
3971 // Make a named function.
3972
3973 Named_object*
3974 Named_object::make_function(const std::string& name, const Package* package,
3975                             Function* function)
3976 {
3977   Named_object* named_object = new Named_object(name, package,
3978                                                 NAMED_OBJECT_FUNC);
3979   named_object->u_.func_value = function;
3980   return named_object;
3981 }
3982
3983 // Make a function declaration.
3984
3985 Named_object*
3986 Named_object::make_function_declaration(const std::string& name,
3987                                         const Package* package,
3988                                         Function_type* fntype,
3989                                         source_location location)
3990 {
3991   Named_object* named_object = new Named_object(name, package,
3992                                                 NAMED_OBJECT_FUNC_DECLARATION);
3993   Function_declaration *func_decl = new Function_declaration(fntype, location);
3994   named_object->u_.func_declaration_value = func_decl;
3995   return named_object;
3996 }
3997
3998 // Make a package.
3999
4000 Named_object*
4001 Named_object::make_package(const std::string& alias, Package* package)
4002 {
4003   Named_object* named_object = new Named_object(alias, NULL,
4004                                                 NAMED_OBJECT_PACKAGE);
4005   named_object->u_.package_value = package;
4006   return named_object;
4007 }
4008
4009 // Return the name to use in an error message.
4010
4011 std::string
4012 Named_object::message_name() const
4013 {
4014   if (this->package_ == NULL)
4015     return Gogo::message_name(this->name_);
4016   std::string ret = Gogo::message_name(this->package_->name());
4017   ret += '.';
4018   ret += Gogo::message_name(this->name_);
4019   return ret;
4020 }
4021
4022 // Set the type when a declaration is defined.
4023
4024 void
4025 Named_object::set_type_value(Named_type* named_type)
4026 {
4027   gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4028   Type_declaration* td = this->u_.type_declaration;
4029   td->define_methods(named_type);
4030   Named_object* in_function = td->in_function();
4031   if (in_function != NULL)
4032     named_type->set_in_function(in_function);
4033   delete td;
4034   this->classification_ = NAMED_OBJECT_TYPE;
4035   this->u_.type_value = named_type;
4036 }
4037
4038 // Define a function which was previously declared.
4039
4040 void
4041 Named_object::set_function_value(Function* function)
4042 {
4043   gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4044   this->classification_ = NAMED_OBJECT_FUNC;
4045   // FIXME: We should free the old value.
4046   this->u_.func_value = function;
4047 }
4048
4049 // Declare an unknown object as a type declaration.
4050
4051 void
4052 Named_object::declare_as_type()
4053 {
4054   gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4055   Unknown_name* unk = this->u_.unknown_value;
4056   this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4057   this->u_.type_declaration = new Type_declaration(unk->location());
4058   delete unk;
4059 }
4060
4061 // Return the location of a named object.
4062
4063 source_location
4064 Named_object::location() const
4065 {
4066   switch (this->classification_)
4067     {
4068     default:
4069     case NAMED_OBJECT_UNINITIALIZED:
4070       gcc_unreachable();
4071
4072     case NAMED_OBJECT_UNKNOWN:
4073       return this->unknown_value()->location();
4074
4075     case NAMED_OBJECT_CONST:
4076       return this->const_value()->location();
4077
4078     case NAMED_OBJECT_TYPE:
4079       return this->type_value()->location();
4080
4081     case NAMED_OBJECT_TYPE_DECLARATION:
4082       return this->type_declaration_value()->location();
4083
4084     case NAMED_OBJECT_VAR:
4085       return this->var_value()->location();
4086
4087     case NAMED_OBJECT_RESULT_VAR:
4088       return this->result_var_value()->location();
4089
4090     case NAMED_OBJECT_SINK:
4091       gcc_unreachable();
4092
4093     case NAMED_OBJECT_FUNC:
4094       return this->func_value()->location();
4095
4096     case NAMED_OBJECT_FUNC_DECLARATION:
4097       return this->func_declaration_value()->location();
4098
4099     case NAMED_OBJECT_PACKAGE:
4100       return this->package_value()->location();
4101     }
4102 }
4103
4104 // Export a named object.
4105
4106 void
4107 Named_object::export_named_object(Export* exp) const
4108 {
4109   switch (this->classification_)
4110     {
4111     default:
4112     case NAMED_OBJECT_UNINITIALIZED:
4113     case NAMED_OBJECT_UNKNOWN:
4114       gcc_unreachable();
4115
4116     case NAMED_OBJECT_CONST:
4117       this->const_value()->export_const(exp, this->name_);
4118       break;
4119
4120     case NAMED_OBJECT_TYPE:
4121       this->type_value()->export_named_type(exp, this->name_);
4122       break;
4123
4124     case NAMED_OBJECT_TYPE_DECLARATION:
4125       error_at(this->type_declaration_value()->location(),
4126                "attempt to export %<%s%> which was declared but not defined",
4127                this->message_name().c_str());
4128       break;
4129
4130     case NAMED_OBJECT_FUNC_DECLARATION:
4131       this->func_declaration_value()->export_func(exp, this->name_);
4132       break;
4133
4134     case NAMED_OBJECT_VAR:
4135       this->var_value()->export_var(exp, this->name_);
4136       break;
4137
4138     case NAMED_OBJECT_RESULT_VAR:
4139     case NAMED_OBJECT_SINK:
4140       gcc_unreachable();
4141
4142     case NAMED_OBJECT_FUNC:
4143       this->func_value()->export_func(exp, this->name_);
4144       break;
4145     }
4146 }
4147
4148 // Convert a variable to the backend representation.
4149
4150 Bvariable*
4151 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4152 {
4153   if (this->classification_ == NAMED_OBJECT_VAR)
4154     return this->var_value()->get_backend_variable(gogo, function,
4155                                                    this->package_, this->name_);
4156   else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4157     return this->result_var_value()->get_backend_variable(gogo, function,
4158                                                           this->name_);
4159   else
4160     gcc_unreachable();
4161 }
4162
4163 // Class Bindings.
4164
4165 Bindings::Bindings(Bindings* enclosing)
4166   : enclosing_(enclosing), named_objects_(), bindings_()
4167 {
4168 }
4169
4170 // Clear imports.
4171
4172 void
4173 Bindings::clear_file_scope()
4174 {
4175   Contour::iterator p = this->bindings_.begin();
4176   while (p != this->bindings_.end())
4177     {
4178       bool keep;
4179       if (p->second->package() != NULL)
4180         keep = false;
4181       else if (p->second->is_package())
4182         keep = false;
4183       else if (p->second->is_function()
4184                && !p->second->func_value()->type()->is_method()
4185                && Gogo::unpack_hidden_name(p->second->name()) == "init")
4186         keep = false;
4187       else
4188         keep = true;
4189
4190       if (keep)
4191         ++p;
4192       else
4193         p = this->bindings_.erase(p);
4194     }
4195 }
4196
4197 // Look up a symbol.
4198
4199 Named_object*
4200 Bindings::lookup(const std::string& name) const
4201 {
4202   Contour::const_iterator p = this->bindings_.find(name);
4203   if (p != this->bindings_.end())
4204     return p->second->resolve();
4205   else if (this->enclosing_ != NULL)
4206     return this->enclosing_->lookup(name);
4207   else
4208     return NULL;
4209 }
4210
4211 // Look up a symbol locally.
4212
4213 Named_object*
4214 Bindings::lookup_local(const std::string& name) const
4215 {
4216   Contour::const_iterator p = this->bindings_.find(name);
4217   if (p == this->bindings_.end())
4218     return NULL;
4219   return p->second;
4220 }
4221
4222 // Remove an object from a set of bindings.  This is used for a
4223 // special case in thunks for functions which call recover.
4224
4225 void
4226 Bindings::remove_binding(Named_object* no)
4227 {
4228   Contour::iterator pb = this->bindings_.find(no->name());
4229   gcc_assert(pb != this->bindings_.end());
4230   this->bindings_.erase(pb);
4231   for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4232        pn != this->named_objects_.end();
4233        ++pn)
4234     {
4235       if (*pn == no)
4236         {
4237           this->named_objects_.erase(pn);
4238           return;
4239         }
4240     }
4241   gcc_unreachable();
4242 }
4243
4244 // Add a method to the list of objects.  This is not added to the
4245 // lookup table.  This is so that we have a single list of objects
4246 // declared at the top level, which we walk through when it's time to
4247 // convert to trees.
4248
4249 void
4250 Bindings::add_method(Named_object* method)
4251 {
4252   this->named_objects_.push_back(method);
4253 }
4254
4255 // Add a generic Named_object to a Contour.
4256
4257 Named_object*
4258 Bindings::add_named_object_to_contour(Contour* contour,
4259                                       Named_object* named_object)
4260 {
4261   gcc_assert(named_object == named_object->resolve());
4262   const std::string& name(named_object->name());
4263   gcc_assert(!Gogo::is_sink_name(name));
4264
4265   std::pair<Contour::iterator, bool> ins =
4266     contour->insert(std::make_pair(name, named_object));
4267   if (!ins.second)
4268     {
4269       // The name was already there.
4270       if (named_object->package() != NULL
4271           && ins.first->second->package() == named_object->package()
4272           && (ins.first->second->classification()
4273               == named_object->classification()))
4274         {
4275           // This is a second import of the same object.
4276           return ins.first->second;
4277         }
4278       ins.first->second = this->new_definition(ins.first->second,
4279                                                named_object);
4280       return ins.first->second;
4281     }
4282   else
4283     {
4284       // Don't push declarations on the list.  We push them on when
4285       // and if we find the definitions.  That way we genericize the
4286       // functions in order.
4287       if (!named_object->is_type_declaration()
4288           && !named_object->is_function_declaration()
4289           && !named_object->is_unknown())
4290         this->named_objects_.push_back(named_object);
4291       return named_object;
4292     }
4293 }
4294
4295 // We had an existing named object OLD_OBJECT, and we've seen a new
4296 // one NEW_OBJECT with the same name.  FIXME: This does not free the
4297 // new object when we don't need it.
4298
4299 Named_object*
4300 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4301 {
4302   std::string reason;
4303   switch (old_object->classification())
4304     {
4305     default:
4306     case Named_object::NAMED_OBJECT_UNINITIALIZED:
4307       gcc_unreachable();
4308
4309     case Named_object::NAMED_OBJECT_UNKNOWN:
4310       {
4311         Named_object* real = old_object->unknown_value()->real_named_object();
4312         if (real != NULL)
4313           return this->new_definition(real, new_object);
4314         gcc_assert(!new_object->is_unknown());
4315         old_object->unknown_value()->set_real_named_object(new_object);
4316         if (!new_object->is_type_declaration()
4317             && !new_object->is_function_declaration())
4318           this->named_objects_.push_back(new_object);
4319         return new_object;
4320       }
4321
4322     case Named_object::NAMED_OBJECT_CONST:
4323       break;
4324
4325     case Named_object::NAMED_OBJECT_TYPE:
4326       if (new_object->is_type_declaration())
4327         return old_object;
4328       break;
4329
4330     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4331       if (new_object->is_type_declaration())
4332         return old_object;
4333       if (new_object->is_type())
4334         {
4335           old_object->set_type_value(new_object->type_value());
4336           new_object->type_value()->set_named_object(old_object);
4337           this->named_objects_.push_back(old_object);
4338           return old_object;
4339         }
4340       break;
4341
4342     case Named_object::NAMED_OBJECT_VAR:
4343     case Named_object::NAMED_OBJECT_RESULT_VAR:
4344       break;
4345
4346     case Named_object::NAMED_OBJECT_SINK:
4347       gcc_unreachable();
4348
4349     case Named_object::NAMED_OBJECT_FUNC:
4350       if (new_object->is_function_declaration())
4351         {
4352           if (!new_object->func_declaration_value()->asm_name().empty())
4353             sorry("__asm__ for function definitions");
4354           Function_type* old_type = old_object->func_value()->type();
4355           Function_type* new_type =
4356             new_object->func_declaration_value()->type();
4357           if (old_type->is_valid_redeclaration(new_type, &reason))
4358             return old_object;
4359         }
4360       break;
4361
4362     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4363       {
4364         Function_type* old_type = old_object->func_declaration_value()->type();
4365         if (new_object->is_function_declaration())
4366           {
4367             Function_type* new_type =
4368               new_object->func_declaration_value()->type();
4369             if (old_type->is_valid_redeclaration(new_type, &reason))
4370               return old_object;
4371           }
4372         if (new_object->is_function())
4373           {
4374             Function_type* new_type = new_object->func_value()->type();
4375             if (old_type->is_valid_redeclaration(new_type, &reason))
4376               {
4377                 if (!old_object->func_declaration_value()->asm_name().empty())
4378                   sorry("__asm__ for function definitions");
4379                 old_object->set_function_value(new_object->func_value());
4380                 this->named_objects_.push_back(old_object);
4381                 return old_object;
4382               }
4383           }
4384       }
4385       break;
4386
4387     case Named_object::NAMED_OBJECT_PACKAGE:
4388       if (new_object->is_package()
4389           && (old_object->package_value()->name()
4390               == new_object->package_value()->name()))
4391         return old_object;
4392
4393       break;
4394     }
4395
4396   std::string n = old_object->message_name();
4397   if (reason.empty())
4398     error_at(new_object->location(), "redefinition of %qs", n.c_str());
4399   else
4400     error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4401              reason.c_str());
4402
4403   inform(old_object->location(), "previous definition of %qs was here",
4404          n.c_str());
4405
4406   return old_object;
4407 }
4408
4409 // Add a named type.
4410
4411 Named_object*
4412 Bindings::add_named_type(Named_type* named_type)
4413 {
4414   return this->add_named_object(named_type->named_object());
4415 }
4416
4417 // Add a function.
4418
4419 Named_object*
4420 Bindings::add_function(const std::string& name, const Package* package,
4421                        Function* function)
4422 {
4423   return this->add_named_object(Named_object::make_function(name, package,
4424                                                             function));
4425 }
4426
4427 // Add a function declaration.
4428
4429 Named_object*
4430 Bindings::add_function_declaration(const std::string& name,
4431                                    const Package* package,
4432                                    Function_type* type,
4433                                    source_location location)
4434 {
4435   Named_object* no = Named_object::make_function_declaration(name, package,
4436                                                              type, location);
4437   return this->add_named_object(no);
4438 }
4439
4440 // Define a type which was previously declared.
4441
4442 void
4443 Bindings::define_type(Named_object* no, Named_type* type)
4444 {
4445   no->set_type_value(type);
4446   this->named_objects_.push_back(no);
4447 }
4448
4449 // Traverse bindings.
4450
4451 int
4452 Bindings::traverse(Traverse* traverse, bool is_global)
4453 {
4454   unsigned int traverse_mask = traverse->traverse_mask();
4455
4456   // We don't use an iterator because we permit the traversal to add
4457   // new global objects.
4458   for (size_t i = 0; i < this->named_objects_.size(); ++i)
4459     {
4460       Named_object* p = this->named_objects_[i];
4461       switch (p->classification())
4462         {
4463         case Named_object::NAMED_OBJECT_CONST:
4464           if ((traverse_mask & Traverse::traverse_constants) != 0)
4465             {
4466               if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4467                 return TRAVERSE_EXIT;
4468             }
4469           if ((traverse_mask & Traverse::traverse_types) != 0
4470               || (traverse_mask & Traverse::traverse_expressions) != 0)
4471             {
4472               Type* t = p->const_value()->type();
4473               if (t != NULL
4474                   && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4475                 return TRAVERSE_EXIT;
4476               if (p->const_value()->traverse_expression(traverse)
4477                   == TRAVERSE_EXIT)
4478                 return TRAVERSE_EXIT;
4479             }
4480           break;
4481
4482         case Named_object::NAMED_OBJECT_VAR:
4483         case Named_object::NAMED_OBJECT_RESULT_VAR:
4484           if ((traverse_mask & Traverse::traverse_variables) != 0)
4485             {
4486               if (traverse->variable(p) == TRAVERSE_EXIT)
4487                 return TRAVERSE_EXIT;
4488             }
4489           if (((traverse_mask & Traverse::traverse_types) != 0
4490                || (traverse_mask & Traverse::traverse_expressions) != 0)
4491               && (p->is_result_variable()
4492                   || p->var_value()->has_type()))
4493             {
4494               Type* t = (p->is_variable()
4495                          ? p->var_value()->type()
4496                          : p->result_var_value()->type());
4497               if (t != NULL
4498                   && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4499                 return TRAVERSE_EXIT;
4500             }
4501           if (p->is_variable()
4502               && ((traverse_mask & Traverse::traverse_types) != 0
4503                   || (traverse_mask & Traverse::traverse_expressions) != 0))
4504             {
4505               if (p->var_value()->traverse_expression(traverse)
4506                   == TRAVERSE_EXIT)
4507                 return TRAVERSE_EXIT;
4508             }
4509           break;
4510
4511         case Named_object::NAMED_OBJECT_FUNC:
4512           if ((traverse_mask & Traverse::traverse_functions) != 0)
4513             {
4514               int t = traverse->function(p);
4515               if (t == TRAVERSE_EXIT)
4516                 return TRAVERSE_EXIT;
4517               else if (t == TRAVERSE_SKIP_COMPONENTS)
4518                 break;
4519             }
4520
4521           if ((traverse_mask
4522                & (Traverse::traverse_variables
4523                   | Traverse::traverse_constants
4524                   | Traverse::traverse_functions
4525                   | Traverse::traverse_blocks
4526                   | Traverse::traverse_statements
4527                   | Traverse::traverse_expressions
4528                   | Traverse::traverse_types)) != 0)
4529             {
4530               if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4531                 return TRAVERSE_EXIT;
4532             }
4533           break;
4534
4535         case Named_object::NAMED_OBJECT_PACKAGE:
4536           // These are traversed in Gogo::traverse.
4537           gcc_assert(is_global);
4538           break;
4539
4540         case Named_object::NAMED_OBJECT_TYPE:
4541           if ((traverse_mask & Traverse::traverse_types) != 0
4542               || (traverse_mask & Traverse::traverse_expressions) != 0)
4543             {
4544               if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4545                 return TRAVERSE_EXIT;
4546             }
4547           break;
4548
4549         case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4550         case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4551         case Named_object::NAMED_OBJECT_UNKNOWN:
4552           break;
4553
4554         case Named_object::NAMED_OBJECT_SINK:
4555         default:
4556           gcc_unreachable();
4557         }
4558     }
4559
4560   return TRAVERSE_CONTINUE;
4561 }
4562
4563 // Class Label.
4564
4565 // Get the backend representation for a label.
4566
4567 Blabel*
4568 Label::get_backend_label(Translate_context* context)
4569 {
4570   if (this->blabel_ == NULL)
4571     {
4572       Function* function = context->function()->func_value();
4573       tree fndecl = function->get_decl();
4574       Bfunction* bfunction = tree_to_function(fndecl);
4575       this->blabel_ = context->backend()->label(bfunction, this->name_,
4576                                                 this->location_);
4577     }
4578   return this->blabel_;
4579 }
4580
4581 // Return an expression for the address of this label.
4582
4583 Bexpression*
4584 Label::get_addr(Translate_context* context, source_location location)
4585 {
4586   Blabel* label = this->get_backend_label(context);
4587   return context->backend()->label_address(label, location);
4588 }
4589
4590 // Class Unnamed_label.
4591
4592 // Get the backend representation for an unnamed label.
4593
4594 Blabel*
4595 Unnamed_label::get_blabel(Translate_context* context)
4596 {
4597   if (this->blabel_ == NULL)
4598     {
4599       Function* function = context->function()->func_value();
4600       tree fndecl = function->get_decl();
4601       Bfunction* bfunction = tree_to_function(fndecl);
4602       this->blabel_ = context->backend()->label(bfunction, "",
4603                                                 this->location_);
4604     }
4605   return this->blabel_;
4606 }
4607
4608 // Return a statement which defines this unnamed label.
4609
4610 Bstatement*
4611 Unnamed_label::get_definition(Translate_context* context)
4612 {
4613   Blabel* blabel = this->get_blabel(context);
4614   return context->backend()->label_definition_statement(blabel);
4615 }
4616
4617 // Return a goto statement to this unnamed label.
4618
4619 Bstatement*
4620 Unnamed_label::get_goto(Translate_context* context, source_location location)
4621 {
4622   Blabel* blabel = this->get_blabel(context);
4623   return context->backend()->goto_statement(blabel, location);
4624 }
4625
4626 // Class Package.
4627
4628 Package::Package(const std::string& name, const std::string& unique_prefix,
4629                  source_location location)
4630   : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4631     priority_(0), location_(location), used_(false), is_imported_(false),
4632     uses_sink_alias_(false)
4633 {
4634   gcc_assert(!name.empty() && !unique_prefix.empty());
4635 }
4636
4637 // Set the priority.  We may see multiple priorities for an imported
4638 // package; we want to use the largest one.
4639
4640 void
4641 Package::set_priority(int priority)
4642 {
4643   if (priority > this->priority_)
4644     this->priority_ = priority;
4645 }
4646
4647 // Determine types of constants.  Everything else in a package
4648 // (variables, function declarations) should already have a fixed
4649 // type.  Constants may have abstract types.
4650
4651 void
4652 Package::determine_types()
4653 {
4654   Bindings* bindings = this->bindings_;
4655   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4656        p != bindings->end_definitions();
4657        ++p)
4658     {
4659       if ((*p)->is_const())
4660         (*p)->const_value()->determine_type();
4661     }
4662 }
4663
4664 // Class Traverse.
4665
4666 // Destructor.
4667
4668 Traverse::~Traverse()
4669 {
4670   if (this->types_seen_ != NULL)
4671     delete this->types_seen_;
4672   if (this->expressions_seen_ != NULL)
4673     delete this->expressions_seen_;
4674 }
4675
4676 // Record that we are looking at a type, and return true if we have
4677 // already seen it.
4678
4679 bool
4680 Traverse::remember_type(const Type* type)
4681 {
4682   if (type->is_error_type())
4683     return true;
4684   gcc_assert((this->traverse_mask() & traverse_types) != 0
4685              || (this->traverse_mask() & traverse_expressions) != 0);
4686   // We only have to remember named types, as they are the only ones
4687   // we can see multiple times in a traversal.
4688   if (type->classification() != Type::TYPE_NAMED)
4689     return false;
4690   if (this->types_seen_ == NULL)
4691     this->types_seen_ = new Types_seen();
4692   std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4693   return !ins.second;
4694 }
4695
4696 // Record that we are looking at an expression, and return true if we
4697 // have already seen it.
4698
4699 bool
4700 Traverse::remember_expression(const Expression* expression)
4701 {
4702   gcc_assert((this->traverse_mask() & traverse_types) != 0
4703              || (this->traverse_mask() & traverse_expressions) != 0);
4704   if (this->expressions_seen_ == NULL)
4705     this->expressions_seen_ = new Expressions_seen();
4706   std::pair<Expressions_seen::iterator, bool> ins =
4707     this->expressions_seen_->insert(expression);
4708   return !ins.second;
4709 }
4710
4711 // The default versions of these functions should never be called: the
4712 // traversal mask indicates which functions may be called.
4713
4714 int
4715 Traverse::variable(Named_object*)
4716 {
4717   gcc_unreachable();
4718 }
4719
4720 int
4721 Traverse::constant(Named_object*, bool)
4722 {
4723   gcc_unreachable();
4724 }
4725
4726 int
4727 Traverse::function(Named_object*)
4728 {
4729   gcc_unreachable();
4730 }
4731
4732 int
4733 Traverse::block(Block*)
4734 {
4735   gcc_unreachable();
4736 }
4737
4738 int
4739 Traverse::statement(Block*, size_t*, Statement*)
4740 {
4741   gcc_unreachable();
4742 }
4743
4744 int
4745 Traverse::expression(Expression**)
4746 {
4747   gcc_unreachable();
4748 }
4749
4750 int
4751 Traverse::type(Type*)
4752 {
4753   gcc_unreachable();
4754 }