OSDN Git Service

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