OSDN Git Service

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