OSDN Git Service

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