compiler: Add support for method values.
[official-gcc.git] / gcc / go / gofrontend / gogo.cc
blob24f890cdef98529c69c74d2d08d1a058fb75be04
1 // gogo.cc -- Go frontend parsed representation.
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.
7 #include "go-system.h"
9 #include "filenames.h"
11 #include "go-c.h"
12 #include "go-dump.h"
13 #include "lex.h"
14 #include "types.h"
15 #include "statements.h"
16 #include "expressions.h"
17 #include "dataflow.h"
18 #include "runtime.h"
19 #include "import.h"
20 #include "export.h"
21 #include "backend.h"
22 #include "gogo.h"
24 // Class Gogo.
26 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
27 : backend_(backend),
28 linemap_(linemap),
29 package_(NULL),
30 functions_(),
31 globals_(new Bindings(NULL)),
32 file_block_names_(),
33 imports_(),
34 imported_unsafe_(false),
35 packages_(),
36 init_functions_(),
37 var_deps_(),
38 need_init_fn_(false),
39 init_fn_name_(),
40 imported_init_fns_(),
41 pkgpath_(),
42 pkgpath_symbol_(),
43 prefix_(),
44 pkgpath_set_(false),
45 pkgpath_from_option_(false),
46 prefix_from_option_(false),
47 relative_import_path_(),
48 verify_types_(),
49 interface_types_(),
50 specific_type_functions_(),
51 specific_type_functions_are_written_(false),
52 named_types_are_converted_(false)
54 const Location loc = Linemap::predeclared_location();
56 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
57 RUNTIME_TYPE_KIND_UINT8);
58 this->add_named_type(uint8_type);
59 this->add_named_type(Type::make_integer_type("uint16", true, 16,
60 RUNTIME_TYPE_KIND_UINT16));
61 this->add_named_type(Type::make_integer_type("uint32", true, 32,
62 RUNTIME_TYPE_KIND_UINT32));
63 this->add_named_type(Type::make_integer_type("uint64", true, 64,
64 RUNTIME_TYPE_KIND_UINT64));
66 this->add_named_type(Type::make_integer_type("int8", false, 8,
67 RUNTIME_TYPE_KIND_INT8));
68 this->add_named_type(Type::make_integer_type("int16", false, 16,
69 RUNTIME_TYPE_KIND_INT16));
70 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
71 RUNTIME_TYPE_KIND_INT32);
72 this->add_named_type(int32_type);
73 this->add_named_type(Type::make_integer_type("int64", false, 64,
74 RUNTIME_TYPE_KIND_INT64));
76 this->add_named_type(Type::make_float_type("float32", 32,
77 RUNTIME_TYPE_KIND_FLOAT32));
78 this->add_named_type(Type::make_float_type("float64", 64,
79 RUNTIME_TYPE_KIND_FLOAT64));
81 this->add_named_type(Type::make_complex_type("complex64", 64,
82 RUNTIME_TYPE_KIND_COMPLEX64));
83 this->add_named_type(Type::make_complex_type("complex128", 128,
84 RUNTIME_TYPE_KIND_COMPLEX128));
86 int int_type_size = pointer_size;
87 if (int_type_size < 32)
88 int_type_size = 32;
89 this->add_named_type(Type::make_integer_type("uint", true,
90 int_type_size,
91 RUNTIME_TYPE_KIND_UINT));
92 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
93 RUNTIME_TYPE_KIND_INT);
94 this->add_named_type(int_type);
96 this->add_named_type(Type::make_integer_type("uintptr", true,
97 pointer_size,
98 RUNTIME_TYPE_KIND_UINTPTR));
100 // "byte" is an alias for "uint8".
101 uint8_type->integer_type()->set_is_byte();
102 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
103 loc);
104 this->add_named_type(byte_type->type_value());
106 // "rune" is an alias for "int32".
107 int32_type->integer_type()->set_is_rune();
108 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
109 loc);
110 this->add_named_type(rune_type->type_value());
112 this->add_named_type(Type::make_named_bool_type());
114 this->add_named_type(Type::make_named_string_type());
116 // "error" is interface { Error() string }.
118 Typed_identifier_list *methods = new Typed_identifier_list;
119 Typed_identifier_list *results = new Typed_identifier_list;
120 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
121 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
122 methods->push_back(Typed_identifier("Error", method_type, loc));
123 Interface_type *error_iface = Type::make_interface_type(methods, loc);
124 error_iface->finalize_methods();
125 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
126 this->add_named_type(error_type);
129 this->globals_->add_constant(Typed_identifier("true",
130 Type::make_boolean_type(),
131 loc),
132 NULL,
133 Expression::make_boolean(true, loc),
135 this->globals_->add_constant(Typed_identifier("false",
136 Type::make_boolean_type(),
137 loc),
138 NULL,
139 Expression::make_boolean(false, loc),
142 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
143 loc),
144 NULL,
145 Expression::make_nil(loc),
148 Type* abstract_int_type = Type::make_abstract_integer_type();
149 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
150 loc),
151 NULL,
152 Expression::make_iota(),
155 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
156 new_type->set_is_varargs();
157 new_type->set_is_builtin();
158 this->globals_->add_function_declaration("new", NULL, new_type, loc);
160 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
161 make_type->set_is_varargs();
162 make_type->set_is_builtin();
163 this->globals_->add_function_declaration("make", NULL, make_type, loc);
165 Typed_identifier_list* len_result = new Typed_identifier_list();
166 len_result->push_back(Typed_identifier("", int_type, loc));
167 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
168 loc);
169 len_type->set_is_builtin();
170 this->globals_->add_function_declaration("len", NULL, len_type, loc);
172 Typed_identifier_list* cap_result = new Typed_identifier_list();
173 cap_result->push_back(Typed_identifier("", int_type, loc));
174 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
175 loc);
176 cap_type->set_is_builtin();
177 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
179 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
180 print_type->set_is_varargs();
181 print_type->set_is_builtin();
182 this->globals_->add_function_declaration("print", NULL, print_type, loc);
184 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
185 print_type->set_is_varargs();
186 print_type->set_is_builtin();
187 this->globals_->add_function_declaration("println", NULL, print_type, loc);
189 Type *empty = Type::make_empty_interface_type(loc);
190 Typed_identifier_list* panic_parms = new Typed_identifier_list();
191 panic_parms->push_back(Typed_identifier("e", empty, loc));
192 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
193 NULL, loc);
194 panic_type->set_is_builtin();
195 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
197 Typed_identifier_list* recover_result = new Typed_identifier_list();
198 recover_result->push_back(Typed_identifier("", empty, loc));
199 Function_type* recover_type = Type::make_function_type(NULL, NULL,
200 recover_result,
201 loc);
202 recover_type->set_is_builtin();
203 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
205 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
206 close_type->set_is_varargs();
207 close_type->set_is_builtin();
208 this->globals_->add_function_declaration("close", NULL, close_type, loc);
210 Typed_identifier_list* copy_result = new Typed_identifier_list();
211 copy_result->push_back(Typed_identifier("", int_type, loc));
212 Function_type* copy_type = Type::make_function_type(NULL, NULL,
213 copy_result, loc);
214 copy_type->set_is_varargs();
215 copy_type->set_is_builtin();
216 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
218 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
219 append_type->set_is_varargs();
220 append_type->set_is_builtin();
221 this->globals_->add_function_declaration("append", NULL, append_type, loc);
223 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
224 complex_type->set_is_varargs();
225 complex_type->set_is_builtin();
226 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
228 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
229 real_type->set_is_varargs();
230 real_type->set_is_builtin();
231 this->globals_->add_function_declaration("real", NULL, real_type, loc);
233 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
234 imag_type->set_is_varargs();
235 imag_type->set_is_builtin();
236 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
238 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
239 delete_type->set_is_varargs();
240 delete_type->set_is_builtin();
241 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
244 // Convert a pkgpath into a string suitable for a symbol. Note that
245 // this transformation is convenient but imperfect. A -fgo-pkgpath
246 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
247 // possibly leading to link time errors.
249 std::string
250 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
252 std::string s = pkgpath;
253 for (size_t i = 0; i < s.length(); ++i)
255 char c = s[i];
256 if ((c >= 'a' && c <= 'z')
257 || (c >= 'A' && c <= 'Z')
258 || (c >= '0' && c <= '9')
259 || c == '_'
260 || c == '.'
261 || c == '$')
263 else
264 s[i] = '_';
266 return s;
269 // Get the package path to use for type reflection data. This should
270 // ideally be unique across the entire link.
272 const std::string&
273 Gogo::pkgpath() const
275 go_assert(this->pkgpath_set_);
276 return this->pkgpath_;
279 // Set the package path from the -fgo-pkgpath command line option.
281 void
282 Gogo::set_pkgpath(const std::string& arg)
284 go_assert(!this->pkgpath_set_);
285 this->pkgpath_ = arg;
286 this->pkgpath_set_ = true;
287 this->pkgpath_from_option_ = true;
290 // Get the package path to use for symbol names.
292 const std::string&
293 Gogo::pkgpath_symbol() const
295 go_assert(this->pkgpath_set_);
296 return this->pkgpath_symbol_;
299 // Set the unique prefix to use to determine the package path, from
300 // the -fgo-prefix command line option.
302 void
303 Gogo::set_prefix(const std::string& arg)
305 go_assert(!this->prefix_from_option_);
306 this->prefix_ = arg;
307 this->prefix_from_option_ = true;
310 // Munge name for use in an error message.
312 std::string
313 Gogo::message_name(const std::string& name)
315 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
318 // Get the package name.
320 const std::string&
321 Gogo::package_name() const
323 go_assert(this->package_ != NULL);
324 return this->package_->package_name();
327 // Set the package name.
329 void
330 Gogo::set_package_name(const std::string& package_name,
331 Location location)
333 if (this->package_ != NULL)
335 if (this->package_->package_name() != package_name)
336 error_at(location, "expected package %<%s%>",
337 Gogo::message_name(this->package_->package_name()).c_str());
338 return;
341 // Now that we know the name of the package we are compiling, set
342 // the package path to use for reflect.Type.PkgPath and global
343 // symbol names.
344 if (!this->pkgpath_set_)
346 if (!this->prefix_from_option_ && package_name == "main")
347 this->pkgpath_ = package_name;
348 else
350 if (!this->prefix_from_option_)
351 this->prefix_ = "go";
352 this->pkgpath_ = this->prefix_ + '.' + package_name;
354 this->pkgpath_set_ = true;
357 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
359 this->package_ = this->register_package(this->pkgpath_, location);
360 this->package_->set_package_name(package_name, location);
362 if (this->is_main_package())
364 // Declare "main" as a function which takes no parameters and
365 // returns no value.
366 Location uloc = Linemap::unknown_location();
367 this->declare_function(Gogo::pack_hidden_name("main", false),
368 Type::make_function_type (NULL, NULL, NULL, uloc),
369 uloc);
373 // Return whether this is the "main" package. This is not true if
374 // -fgo-pkgpath or -fgo-prefix was used.
376 bool
377 Gogo::is_main_package() const
379 return (this->package_name() == "main"
380 && !this->pkgpath_from_option_
381 && !this->prefix_from_option_);
384 // Import a package.
386 void
387 Gogo::import_package(const std::string& filename,
388 const std::string& local_name,
389 bool is_local_name_exported,
390 Location location)
392 if (filename.empty())
394 error_at(location, "import path is empty");
395 return;
398 const char *pf = filename.data();
399 const char *pend = pf + filename.length();
400 while (pf < pend)
402 unsigned int c;
403 int adv = Lex::fetch_char(pf, &c);
404 if (adv == 0)
406 error_at(location, "import path contains invalid UTF-8 sequence");
407 return;
409 if (c == '\0')
411 error_at(location, "import path contains NUL");
412 return;
414 if (c < 0x20 || c == 0x7f)
416 error_at(location, "import path contains control character");
417 return;
419 if (c == '\\')
421 error_at(location, "import path contains backslash; use slash");
422 return;
424 if (Lex::is_unicode_space(c))
426 error_at(location, "import path contains space character");
427 return;
429 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
431 error_at(location, "import path contains invalid character '%c'", c);
432 return;
434 pf += adv;
437 if (IS_ABSOLUTE_PATH(filename.c_str()))
439 error_at(location, "import path cannot be absolute path");
440 return;
443 if (filename == "unsafe")
445 this->import_unsafe(local_name, is_local_name_exported, location);
446 return;
449 Imports::const_iterator p = this->imports_.find(filename);
450 if (p != this->imports_.end())
452 Package* package = p->second;
453 package->set_location(location);
454 package->set_is_imported();
455 std::string ln = local_name;
456 bool is_ln_exported = is_local_name_exported;
457 if (ln.empty())
459 ln = package->package_name();
460 go_assert(!ln.empty());
461 is_ln_exported = Lex::is_exported_name(ln);
463 if (ln == ".")
465 Bindings* bindings = package->bindings();
466 for (Bindings::const_declarations_iterator p =
467 bindings->begin_declarations();
468 p != bindings->end_declarations();
469 ++p)
470 this->add_named_object(p->second);
472 else if (ln == "_")
473 package->set_uses_sink_alias();
474 else
476 ln = this->pack_hidden_name(ln, is_ln_exported);
477 this->package_->bindings()->add_package(ln, package);
479 return;
482 Import::Stream* stream = Import::open_package(filename, location,
483 this->relative_import_path_);
484 if (stream == NULL)
486 error_at(location, "import file %qs not found", filename.c_str());
487 return;
490 Import imp(stream, location);
491 imp.register_builtin_types(this);
492 Package* package = imp.import(this, local_name, is_local_name_exported);
493 if (package != NULL)
495 if (package->pkgpath() == this->pkgpath())
496 error_at(location,
497 ("imported package uses same package path as package "
498 "being compiled (see -fgo-pkgpath option)"));
500 this->imports_.insert(std::make_pair(filename, package));
501 package->set_is_imported();
504 delete stream;
507 // Add an import control function for an imported package to the list.
509 void
510 Gogo::add_import_init_fn(const std::string& package_name,
511 const std::string& init_name, int prio)
513 for (std::set<Import_init>::const_iterator p =
514 this->imported_init_fns_.begin();
515 p != this->imported_init_fns_.end();
516 ++p)
518 if (p->init_name() == init_name)
520 // If a test of package P1, built as part of package P1,
521 // imports package P2, and P2 imports P1 (perhaps
522 // indirectly), then we will see the same import name with
523 // different import priorities. That is OK, so don't give
524 // an error about it.
525 if (p->package_name() != package_name)
527 error("duplicate package initialization name %qs",
528 Gogo::message_name(init_name).c_str());
529 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
530 Gogo::message_name(p->package_name()).c_str(),
531 p->priority());
532 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
533 Gogo::message_name(package_name).c_str(), prio);
535 return;
539 this->imported_init_fns_.insert(Import_init(package_name, init_name,
540 prio));
543 // Return whether we are at the global binding level.
545 bool
546 Gogo::in_global_scope() const
548 return this->functions_.empty();
551 // Return the current binding contour.
553 Bindings*
554 Gogo::current_bindings()
556 if (!this->functions_.empty())
557 return this->functions_.back().blocks.back()->bindings();
558 else if (this->package_ != NULL)
559 return this->package_->bindings();
560 else
561 return this->globals_;
564 const Bindings*
565 Gogo::current_bindings() const
567 if (!this->functions_.empty())
568 return this->functions_.back().blocks.back()->bindings();
569 else if (this->package_ != NULL)
570 return this->package_->bindings();
571 else
572 return this->globals_;
575 // Return the current block.
577 Block*
578 Gogo::current_block()
580 if (this->functions_.empty())
581 return NULL;
582 else
583 return this->functions_.back().blocks.back();
586 // Look up a name in the current binding contour. If PFUNCTION is not
587 // NULL, set it to the function in which the name is defined, or NULL
588 // if the name is defined in global scope.
590 Named_object*
591 Gogo::lookup(const std::string& name, Named_object** pfunction) const
593 if (pfunction != NULL)
594 *pfunction = NULL;
596 if (Gogo::is_sink_name(name))
597 return Named_object::make_sink();
599 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
600 p != this->functions_.rend();
601 ++p)
603 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
604 if (ret != NULL)
606 if (pfunction != NULL)
607 *pfunction = p->function;
608 return ret;
612 if (this->package_ != NULL)
614 Named_object* ret = this->package_->bindings()->lookup(name);
615 if (ret != NULL)
617 if (ret->package() != NULL)
618 ret->package()->set_used();
619 return ret;
623 // We do not look in the global namespace. If we did, the global
624 // namespace would effectively hide names which were defined in
625 // package scope which we have not yet seen. Instead,
626 // define_global_names is called after parsing is over to connect
627 // undefined names at package scope with names defined at global
628 // scope.
630 return NULL;
633 // Look up a name in the current block, without searching enclosing
634 // blocks.
636 Named_object*
637 Gogo::lookup_in_block(const std::string& name) const
639 go_assert(!this->functions_.empty());
640 go_assert(!this->functions_.back().blocks.empty());
641 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
644 // Look up a name in the global namespace.
646 Named_object*
647 Gogo::lookup_global(const char* name) const
649 return this->globals_->lookup(name);
652 // Add an imported package.
654 Package*
655 Gogo::add_imported_package(const std::string& real_name,
656 const std::string& alias_arg,
657 bool is_alias_exported,
658 const std::string& pkgpath,
659 Location location,
660 bool* padd_to_globals)
662 Package* ret = this->register_package(pkgpath, location);
663 ret->set_package_name(real_name, location);
665 *padd_to_globals = false;
667 if (alias_arg == ".")
668 *padd_to_globals = true;
669 else if (alias_arg == "_")
670 ret->set_uses_sink_alias();
671 else
673 std::string alias = alias_arg;
674 if (alias.empty())
676 alias = real_name;
677 is_alias_exported = Lex::is_exported_name(alias);
679 alias = this->pack_hidden_name(alias, is_alias_exported);
680 Named_object* no = this->package_->bindings()->add_package(alias, ret);
681 if (!no->is_package())
682 return NULL;
685 return ret;
688 // Register a package. This package may or may not be imported. This
689 // returns the Package structure for the package, creating if it
690 // necessary. LOCATION is the location of the import statement that
691 // led us to see this package.
693 Package*
694 Gogo::register_package(const std::string& pkgpath, Location location)
696 Package* package = NULL;
697 std::pair<Packages::iterator, bool> ins =
698 this->packages_.insert(std::make_pair(pkgpath, package));
699 if (!ins.second)
701 // We have seen this package name before.
702 package = ins.first->second;
703 go_assert(package != NULL && package->pkgpath() == pkgpath);
704 if (Linemap::is_unknown_location(package->location()))
705 package->set_location(location);
707 else
709 // First time we have seen this package name.
710 package = new Package(pkgpath, location);
711 go_assert(ins.first->second == NULL);
712 ins.first->second = package;
715 return package;
718 // Start compiling a function.
720 Named_object*
721 Gogo::start_function(const std::string& name, Function_type* type,
722 bool add_method_to_type, Location location)
724 bool at_top_level = this->functions_.empty();
726 Block* block = new Block(NULL, location);
728 Function* enclosing = (at_top_level
729 ? NULL
730 : this->functions_.back().function->func_value());
732 Function* function = new Function(type, enclosing, block, location);
734 if (type->is_method())
736 const Typed_identifier* receiver = type->receiver();
737 Variable* this_param = new Variable(receiver->type(), NULL, false,
738 true, true, location);
739 std::string rname = receiver->name();
740 if (rname.empty() || Gogo::is_sink_name(rname))
742 // We need to give receivers a name since they wind up in
743 // DECL_ARGUMENTS. FIXME.
744 static unsigned int count;
745 char buf[50];
746 snprintf(buf, sizeof buf, "r.%u", count);
747 ++count;
748 rname = buf;
750 block->bindings()->add_variable(rname, NULL, this_param);
753 const Typed_identifier_list* parameters = type->parameters();
754 bool is_varargs = type->is_varargs();
755 if (parameters != NULL)
757 for (Typed_identifier_list::const_iterator p = parameters->begin();
758 p != parameters->end();
759 ++p)
761 Variable* param = new Variable(p->type(), NULL, false, true, false,
762 location);
763 if (is_varargs && p + 1 == parameters->end())
764 param->set_is_varargs_parameter();
766 std::string pname = p->name();
767 if (pname.empty() || Gogo::is_sink_name(pname))
769 // We need to give parameters a name since they wind up
770 // in DECL_ARGUMENTS. FIXME.
771 static unsigned int count;
772 char buf[50];
773 snprintf(buf, sizeof buf, "p.%u", count);
774 ++count;
775 pname = buf;
777 block->bindings()->add_variable(pname, NULL, param);
781 function->create_result_variables(this);
783 const std::string* pname;
784 std::string nested_name;
785 bool is_init = false;
786 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
788 if ((type->parameters() != NULL && !type->parameters()->empty())
789 || (type->results() != NULL && !type->results()->empty()))
790 error_at(location,
791 "func init must have no arguments and no return values");
792 // There can be multiple "init" functions, so give them each a
793 // different name.
794 static int init_count;
795 char buf[30];
796 snprintf(buf, sizeof buf, ".$init%d", init_count);
797 ++init_count;
798 nested_name = buf;
799 pname = &nested_name;
800 is_init = true;
802 else if (!name.empty())
803 pname = &name;
804 else
806 // Invent a name for a nested function.
807 static int nested_count;
808 char buf[30];
809 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
810 ++nested_count;
811 nested_name = buf;
812 pname = &nested_name;
815 Named_object* ret;
816 if (Gogo::is_sink_name(*pname))
818 static int sink_count;
819 char buf[30];
820 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
821 ++sink_count;
822 ret = this->package_->bindings()->add_function(buf, NULL, function);
823 ret->func_value()->set_is_sink();
825 else if (!type->is_method())
827 ret = this->package_->bindings()->add_function(*pname, NULL, function);
828 if (!ret->is_function() || ret->func_value() != function)
830 // Redefinition error. Invent a name to avoid knockon
831 // errors.
832 static int redefinition_count;
833 char buf[30];
834 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
835 ++redefinition_count;
836 ret = this->package_->bindings()->add_function(buf, NULL, function);
839 else
841 if (!add_method_to_type)
842 ret = Named_object::make_function(name, NULL, function);
843 else
845 go_assert(at_top_level);
846 Type* rtype = type->receiver()->type();
848 // We want to look through the pointer created by the
849 // parser, without getting an error if the type is not yet
850 // defined.
851 if (rtype->classification() == Type::TYPE_POINTER)
852 rtype = rtype->points_to();
854 if (rtype->is_error_type())
855 ret = Named_object::make_function(name, NULL, function);
856 else if (rtype->named_type() != NULL)
858 ret = rtype->named_type()->add_method(name, function);
859 if (!ret->is_function())
861 // Redefinition error.
862 ret = Named_object::make_function(name, NULL, function);
865 else if (rtype->forward_declaration_type() != NULL)
867 Named_object* type_no =
868 rtype->forward_declaration_type()->named_object();
869 if (type_no->is_unknown())
871 // If we are seeing methods it really must be a
872 // type. Declare it as such. An alternative would
873 // be to support lists of methods for unknown
874 // expressions. Either way the error messages if
875 // this is not a type are going to get confusing.
876 Named_object* declared =
877 this->declare_package_type(type_no->name(),
878 type_no->location());
879 go_assert(declared
880 == type_no->unknown_value()->real_named_object());
882 ret = rtype->forward_declaration_type()->add_method(name,
883 function);
885 else
886 go_unreachable();
888 this->package_->bindings()->add_method(ret);
891 this->functions_.resize(this->functions_.size() + 1);
892 Open_function& of(this->functions_.back());
893 of.function = ret;
894 of.blocks.push_back(block);
896 if (is_init)
898 this->init_functions_.push_back(ret);
899 this->need_init_fn_ = true;
902 return ret;
905 // Finish compiling a function.
907 void
908 Gogo::finish_function(Location location)
910 this->finish_block(location);
911 go_assert(this->functions_.back().blocks.empty());
912 this->functions_.pop_back();
915 // Return the current function.
917 Named_object*
918 Gogo::current_function() const
920 go_assert(!this->functions_.empty());
921 return this->functions_.back().function;
924 // Start a new block.
926 void
927 Gogo::start_block(Location location)
929 go_assert(!this->functions_.empty());
930 Block* block = new Block(this->current_block(), location);
931 this->functions_.back().blocks.push_back(block);
934 // Finish a block.
936 Block*
937 Gogo::finish_block(Location location)
939 go_assert(!this->functions_.empty());
940 go_assert(!this->functions_.back().blocks.empty());
941 Block* block = this->functions_.back().blocks.back();
942 this->functions_.back().blocks.pop_back();
943 block->set_end_location(location);
944 return block;
947 // Add an erroneous name.
949 Named_object*
950 Gogo::add_erroneous_name(const std::string& name)
952 return this->package_->bindings()->add_erroneous_name(name);
955 // Add an unknown name.
957 Named_object*
958 Gogo::add_unknown_name(const std::string& name, Location location)
960 return this->package_->bindings()->add_unknown_name(name, location);
963 // Declare a function.
965 Named_object*
966 Gogo::declare_function(const std::string& name, Function_type* type,
967 Location location)
969 if (!type->is_method())
970 return this->current_bindings()->add_function_declaration(name, NULL, type,
971 location);
972 else
974 // We don't bother to add this to the list of global
975 // declarations.
976 Type* rtype = type->receiver()->type();
978 // We want to look through the pointer created by the
979 // parser, without getting an error if the type is not yet
980 // defined.
981 if (rtype->classification() == Type::TYPE_POINTER)
982 rtype = rtype->points_to();
984 if (rtype->is_error_type())
985 return NULL;
986 else if (rtype->named_type() != NULL)
987 return rtype->named_type()->add_method_declaration(name, NULL, type,
988 location);
989 else if (rtype->forward_declaration_type() != NULL)
991 Forward_declaration_type* ftype = rtype->forward_declaration_type();
992 return ftype->add_method_declaration(name, NULL, type, location);
994 else
995 go_unreachable();
999 // Add a label definition.
1001 Label*
1002 Gogo::add_label_definition(const std::string& label_name,
1003 Location location)
1005 go_assert(!this->functions_.empty());
1006 Function* func = this->functions_.back().function->func_value();
1007 Label* label = func->add_label_definition(this, label_name, location);
1008 this->add_statement(Statement::make_label_statement(label, location));
1009 return label;
1012 // Add a label reference.
1014 Label*
1015 Gogo::add_label_reference(const std::string& label_name,
1016 Location location, bool issue_goto_errors)
1018 go_assert(!this->functions_.empty());
1019 Function* func = this->functions_.back().function->func_value();
1020 return func->add_label_reference(this, label_name, location,
1021 issue_goto_errors);
1024 // Return the current binding state.
1026 Bindings_snapshot*
1027 Gogo::bindings_snapshot(Location location)
1029 return new Bindings_snapshot(this->current_block(), location);
1032 // Add a statement.
1034 void
1035 Gogo::add_statement(Statement* statement)
1037 go_assert(!this->functions_.empty()
1038 && !this->functions_.back().blocks.empty());
1039 this->functions_.back().blocks.back()->add_statement(statement);
1042 // Add a block.
1044 void
1045 Gogo::add_block(Block* block, Location location)
1047 go_assert(!this->functions_.empty()
1048 && !this->functions_.back().blocks.empty());
1049 Statement* statement = Statement::make_block_statement(block, location);
1050 this->functions_.back().blocks.back()->add_statement(statement);
1053 // Add a constant.
1055 Named_object*
1056 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
1057 int iota_value)
1059 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
1062 // Add a type.
1064 void
1065 Gogo::add_type(const std::string& name, Type* type, Location location)
1067 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
1068 location);
1069 if (!this->in_global_scope() && no->is_type())
1071 Named_object* f = this->functions_.back().function;
1072 unsigned int index;
1073 if (f->is_function())
1074 index = f->func_value()->new_local_type_index();
1075 else
1076 index = 0;
1077 no->type_value()->set_in_function(f, index);
1081 // Add a named type.
1083 void
1084 Gogo::add_named_type(Named_type* type)
1086 go_assert(this->in_global_scope());
1087 this->current_bindings()->add_named_type(type);
1090 // Declare a type.
1092 Named_object*
1093 Gogo::declare_type(const std::string& name, Location location)
1095 Bindings* bindings = this->current_bindings();
1096 Named_object* no = bindings->add_type_declaration(name, NULL, location);
1097 if (!this->in_global_scope() && no->is_type_declaration())
1099 Named_object* f = this->functions_.back().function;
1100 unsigned int index;
1101 if (f->is_function())
1102 index = f->func_value()->new_local_type_index();
1103 else
1104 index = 0;
1105 no->type_declaration_value()->set_in_function(f, index);
1107 return no;
1110 // Declare a type at the package level.
1112 Named_object*
1113 Gogo::declare_package_type(const std::string& name, Location location)
1115 return this->package_->bindings()->add_type_declaration(name, NULL, location);
1118 // Declare a function at the package level.
1120 Named_object*
1121 Gogo::declare_package_function(const std::string& name, Function_type* type,
1122 Location location)
1124 return this->package_->bindings()->add_function_declaration(name, NULL, type,
1125 location);
1128 // Define a type which was already declared.
1130 void
1131 Gogo::define_type(Named_object* no, Named_type* type)
1133 this->current_bindings()->define_type(no, type);
1136 // Add a variable.
1138 Named_object*
1139 Gogo::add_variable(const std::string& name, Variable* variable)
1141 Named_object* no = this->current_bindings()->add_variable(name, NULL,
1142 variable);
1144 // In a function the middle-end wants to see a DECL_EXPR node.
1145 if (no != NULL
1146 && no->is_variable()
1147 && !no->var_value()->is_parameter()
1148 && !this->functions_.empty())
1149 this->add_statement(Statement::make_variable_declaration(no));
1151 return no;
1154 // Add a sink--a reference to the blank identifier _.
1156 Named_object*
1157 Gogo::add_sink()
1159 return Named_object::make_sink();
1162 // Add a named object.
1164 void
1165 Gogo::add_named_object(Named_object* no)
1167 this->current_bindings()->add_named_object(no);
1170 // Mark all local variables used. This is used when some types of
1171 // parse error occur.
1173 void
1174 Gogo::mark_locals_used()
1176 for (Open_functions::iterator pf = this->functions_.begin();
1177 pf != this->functions_.end();
1178 ++pf)
1180 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
1181 pb != pf->blocks.end();
1182 ++pb)
1183 (*pb)->bindings()->mark_locals_used();
1187 // Record that we've seen an interface type.
1189 void
1190 Gogo::record_interface_type(Interface_type* itype)
1192 this->interface_types_.push_back(itype);
1195 // Return a name for a thunk object.
1197 std::string
1198 Gogo::thunk_name()
1200 static int thunk_count;
1201 char thunk_name[50];
1202 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1203 ++thunk_count;
1204 return thunk_name;
1207 // Return whether a function is a thunk.
1209 bool
1210 Gogo::is_thunk(const Named_object* no)
1212 return no->name().compare(0, 6, "$thunk") == 0;
1215 // Define the global names. We do this only after parsing all the
1216 // input files, because the program might define the global names
1217 // itself.
1219 void
1220 Gogo::define_global_names()
1222 for (Bindings::const_declarations_iterator p =
1223 this->globals_->begin_declarations();
1224 p != this->globals_->end_declarations();
1225 ++p)
1227 Named_object* global_no = p->second;
1228 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1229 Named_object* no = this->package_->bindings()->lookup(name);
1230 if (no == NULL)
1231 continue;
1232 no = no->resolve();
1233 if (no->is_type_declaration())
1235 if (global_no->is_type())
1237 if (no->type_declaration_value()->has_methods())
1238 error_at(no->location(),
1239 "may not define methods for global type");
1240 no->set_type_value(global_no->type_value());
1242 else
1244 error_at(no->location(), "expected type");
1245 Type* errtype = Type::make_error_type();
1246 Named_object* err =
1247 Named_object::make_type("erroneous_type", NULL, errtype,
1248 Linemap::predeclared_location());
1249 no->set_type_value(err->type_value());
1252 else if (no->is_unknown())
1253 no->unknown_value()->set_real_named_object(global_no);
1256 // Give an error if any name is defined in both the package block
1257 // and the file block. For example, this can happen if one file
1258 // imports "fmt" and another file defines a global variable fmt.
1259 for (Bindings::const_declarations_iterator p =
1260 this->package_->bindings()->begin_declarations();
1261 p != this->package_->bindings()->end_declarations();
1262 ++p)
1264 if (p->second->is_unknown()
1265 && p->second->unknown_value()->real_named_object() == NULL)
1267 // No point in warning about an undefined name, as we will
1268 // get other errors later anyhow.
1269 continue;
1271 File_block_names::const_iterator pf =
1272 this->file_block_names_.find(p->second->name());
1273 if (pf != this->file_block_names_.end())
1275 std::string n = p->second->message_name();
1276 error_at(p->second->location(),
1277 "%qs defined as both imported name and global name",
1278 n.c_str());
1279 inform(pf->second, "%qs imported here", n.c_str());
1284 // Clear out names in file scope.
1286 void
1287 Gogo::clear_file_scope()
1289 this->package_->bindings()->clear_file_scope(this);
1291 // Warn about packages which were imported but not used.
1292 bool quiet = saw_errors();
1293 for (Packages::iterator p = this->packages_.begin();
1294 p != this->packages_.end();
1295 ++p)
1297 Package* package = p->second;
1298 if (package != this->package_
1299 && package->is_imported()
1300 && !package->used()
1301 && !package->uses_sink_alias()
1302 && !quiet)
1303 error_at(package->location(), "imported and not used: %s",
1304 Gogo::message_name(package->package_name()).c_str());
1305 package->clear_is_imported();
1306 package->clear_uses_sink_alias();
1307 package->clear_used();
1311 // Queue up a type specific function for later writing. These are
1312 // written out in write_specific_type_functions, called after the
1313 // parse tree is lowered.
1315 void
1316 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1317 const std::string& hash_name,
1318 Function_type* hash_fntype,
1319 const std::string& equal_name,
1320 Function_type* equal_fntype)
1322 go_assert(!this->specific_type_functions_are_written_);
1323 go_assert(!this->in_global_scope());
1324 Specific_type_function* tsf = new Specific_type_function(type, name,
1325 hash_name,
1326 hash_fntype,
1327 equal_name,
1328 equal_fntype);
1329 this->specific_type_functions_.push_back(tsf);
1332 // Look for types which need specific hash or equality functions.
1334 class Specific_type_functions : public Traverse
1336 public:
1337 Specific_type_functions(Gogo* gogo)
1338 : Traverse(traverse_types),
1339 gogo_(gogo)
1343 type(Type*);
1345 private:
1346 Gogo* gogo_;
1350 Specific_type_functions::type(Type* t)
1352 Named_object* hash_fn;
1353 Named_object* equal_fn;
1354 switch (t->classification())
1356 case Type::TYPE_NAMED:
1358 Named_type* nt = t->named_type();
1359 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1360 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
1362 // If this is a struct type, we don't want to make functions
1363 // for the unnamed struct.
1364 Type* rt = nt->real_type();
1365 if (rt->struct_type() == NULL)
1367 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1368 return TRAVERSE_EXIT;
1370 else
1372 // If this type is defined in another package, then we don't
1373 // need to worry about the unexported fields.
1374 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
1375 const Struct_field_list* fields = rt->struct_type()->fields();
1376 for (Struct_field_list::const_iterator p = fields->begin();
1377 p != fields->end();
1378 ++p)
1380 if (is_defined_elsewhere
1381 && Gogo::is_hidden_name(p->field_name()))
1382 continue;
1383 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
1384 return TRAVERSE_EXIT;
1388 return TRAVERSE_SKIP_COMPONENTS;
1391 case Type::TYPE_STRUCT:
1392 case Type::TYPE_ARRAY:
1393 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1394 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1395 break;
1397 default:
1398 break;
1401 return TRAVERSE_CONTINUE;
1404 // Write out type specific functions.
1406 void
1407 Gogo::write_specific_type_functions()
1409 Specific_type_functions stf(this);
1410 this->traverse(&stf);
1412 while (!this->specific_type_functions_.empty())
1414 Specific_type_function* tsf = this->specific_type_functions_.back();
1415 this->specific_type_functions_.pop_back();
1416 tsf->type->write_specific_type_functions(this, tsf->name,
1417 tsf->hash_name,
1418 tsf->hash_fntype,
1419 tsf->equal_name,
1420 tsf->equal_fntype);
1421 delete tsf;
1423 this->specific_type_functions_are_written_ = true;
1426 // Traverse the tree.
1428 void
1429 Gogo::traverse(Traverse* traverse)
1431 // Traverse the current package first for consistency. The other
1432 // packages will only contain imported types, constants, and
1433 // declarations.
1434 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1435 return;
1436 for (Packages::const_iterator p = this->packages_.begin();
1437 p != this->packages_.end();
1438 ++p)
1440 if (p->second != this->package_)
1442 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1443 break;
1448 // Add a type to verify. This is used for types of sink variables, in
1449 // order to give appropriate error messages.
1451 void
1452 Gogo::add_type_to_verify(Type* type)
1454 this->verify_types_.push_back(type);
1457 // Traversal class used to verify types.
1459 class Verify_types : public Traverse
1461 public:
1462 Verify_types()
1463 : Traverse(traverse_types)
1467 type(Type*);
1470 // Verify that a type is correct.
1473 Verify_types::type(Type* t)
1475 if (!t->verify())
1476 return TRAVERSE_SKIP_COMPONENTS;
1477 return TRAVERSE_CONTINUE;
1480 // Verify that all types are correct.
1482 void
1483 Gogo::verify_types()
1485 Verify_types traverse;
1486 this->traverse(&traverse);
1488 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
1489 p != this->verify_types_.end();
1490 ++p)
1491 (*p)->verify();
1492 this->verify_types_.clear();
1495 // Traversal class used to lower parse tree.
1497 class Lower_parse_tree : public Traverse
1499 public:
1500 Lower_parse_tree(Gogo* gogo, Named_object* function)
1501 : Traverse(traverse_variables
1502 | traverse_constants
1503 | traverse_functions
1504 | traverse_statements
1505 | traverse_expressions),
1506 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1509 void
1510 set_inserter(const Statement_inserter* inserter)
1511 { this->inserter_ = *inserter; }
1514 variable(Named_object*);
1517 constant(Named_object*, bool);
1520 function(Named_object*);
1523 statement(Block*, size_t* pindex, Statement*);
1526 expression(Expression**);
1528 private:
1529 // General IR.
1530 Gogo* gogo_;
1531 // The function we are traversing.
1532 Named_object* function_;
1533 // Value to use for the predeclared constant iota.
1534 int iota_value_;
1535 // Current statement inserter for use by expressions.
1536 Statement_inserter inserter_;
1539 // Lower variables.
1542 Lower_parse_tree::variable(Named_object* no)
1544 if (!no->is_variable())
1545 return TRAVERSE_CONTINUE;
1547 if (no->is_variable() && no->var_value()->is_global())
1549 // Global variables can have loops in their initialization
1550 // expressions. This is handled in lower_init_expression.
1551 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1552 &this->inserter_);
1553 return TRAVERSE_CONTINUE;
1556 // This is a local variable. We are going to return
1557 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1558 // initialization expression when we reach the variable declaration
1559 // statement. However, that means that we need to traverse the type
1560 // ourselves.
1561 if (no->var_value()->has_type())
1563 Type* type = no->var_value()->type();
1564 if (type != NULL)
1566 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1567 return TRAVERSE_EXIT;
1570 go_assert(!no->var_value()->has_pre_init());
1572 return TRAVERSE_SKIP_COMPONENTS;
1575 // Lower constants. We handle constants specially so that we can set
1576 // the right value for the predeclared constant iota. This works in
1577 // conjunction with the way we lower Const_expression objects.
1580 Lower_parse_tree::constant(Named_object* no, bool)
1582 Named_constant* nc = no->const_value();
1584 // Don't get into trouble if the constant's initializer expression
1585 // refers to the constant itself.
1586 if (nc->lowering())
1587 return TRAVERSE_CONTINUE;
1588 nc->set_lowering();
1590 go_assert(this->iota_value_ == -1);
1591 this->iota_value_ = nc->iota_value();
1592 nc->traverse_expression(this);
1593 this->iota_value_ = -1;
1595 nc->clear_lowering();
1597 // We will traverse the expression a second time, but that will be
1598 // fast.
1600 return TRAVERSE_CONTINUE;
1603 // Lower the body of a function, and set the closure type. Record the
1604 // function while lowering it, so that we can pass it down when
1605 // lowering an expression.
1608 Lower_parse_tree::function(Named_object* no)
1610 no->func_value()->set_closure_type();
1612 go_assert(this->function_ == NULL);
1613 this->function_ = no;
1614 int t = no->func_value()->traverse(this);
1615 this->function_ = NULL;
1617 if (t == TRAVERSE_EXIT)
1618 return t;
1619 return TRAVERSE_SKIP_COMPONENTS;
1622 // Lower statement parse trees.
1625 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1627 // Because we explicitly traverse the statement's contents
1628 // ourselves, we want to skip block statements here. There is
1629 // nothing to lower in a block statement.
1630 if (sorig->is_block_statement())
1631 return TRAVERSE_CONTINUE;
1633 Statement_inserter hold_inserter(this->inserter_);
1634 this->inserter_ = Statement_inserter(block, pindex);
1636 // Lower the expressions first.
1637 int t = sorig->traverse_contents(this);
1638 if (t == TRAVERSE_EXIT)
1640 this->inserter_ = hold_inserter;
1641 return t;
1644 // Keep lowering until nothing changes.
1645 Statement* s = sorig;
1646 while (true)
1648 Statement* snew = s->lower(this->gogo_, this->function_, block,
1649 &this->inserter_);
1650 if (snew == s)
1651 break;
1652 s = snew;
1653 t = s->traverse_contents(this);
1654 if (t == TRAVERSE_EXIT)
1656 this->inserter_ = hold_inserter;
1657 return t;
1661 if (s != sorig)
1662 block->replace_statement(*pindex, s);
1664 this->inserter_ = hold_inserter;
1665 return TRAVERSE_SKIP_COMPONENTS;
1668 // Lower expression parse trees.
1671 Lower_parse_tree::expression(Expression** pexpr)
1673 // We have to lower all subexpressions first, so that we can get
1674 // their type if necessary. This is awkward, because we don't have
1675 // a postorder traversal pass.
1676 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1677 return TRAVERSE_EXIT;
1678 // Keep lowering until nothing changes.
1679 while (true)
1681 Expression* e = *pexpr;
1682 Expression* enew = e->lower(this->gogo_, this->function_,
1683 &this->inserter_, this->iota_value_);
1684 if (enew == e)
1685 break;
1686 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
1687 return TRAVERSE_EXIT;
1688 *pexpr = enew;
1690 return TRAVERSE_SKIP_COMPONENTS;
1693 // Lower the parse tree. This is called after the parse is complete,
1694 // when all names should be resolved.
1696 void
1697 Gogo::lower_parse_tree()
1699 Lower_parse_tree lower_parse_tree(this, NULL);
1700 this->traverse(&lower_parse_tree);
1703 // Lower a block.
1705 void
1706 Gogo::lower_block(Named_object* function, Block* block)
1708 Lower_parse_tree lower_parse_tree(this, function);
1709 block->traverse(&lower_parse_tree);
1712 // Lower an expression. INSERTER may be NULL, in which case the
1713 // expression had better not need to create any temporaries.
1715 void
1716 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1717 Expression** pexpr)
1719 Lower_parse_tree lower_parse_tree(this, function);
1720 if (inserter != NULL)
1721 lower_parse_tree.set_inserter(inserter);
1722 lower_parse_tree.expression(pexpr);
1725 // Lower a constant. This is called when lowering a reference to a
1726 // constant. We have to make sure that the constant has already been
1727 // lowered.
1729 void
1730 Gogo::lower_constant(Named_object* no)
1732 go_assert(no->is_const());
1733 Lower_parse_tree lower(this, NULL);
1734 lower.constant(no, false);
1737 // Traverse the tree to create function descriptors as needed.
1739 class Create_function_descriptors : public Traverse
1741 public:
1742 Create_function_descriptors(Gogo* gogo)
1743 : Traverse(traverse_functions | traverse_expressions),
1744 gogo_(gogo)
1748 function(Named_object*);
1751 expression(Expression**);
1753 private:
1754 Gogo* gogo_;
1757 // Create a descriptor for every top-level exported function.
1760 Create_function_descriptors::function(Named_object* no)
1762 if (no->is_function()
1763 && no->func_value()->enclosing() == NULL
1764 && !no->func_value()->is_method()
1765 && !no->func_value()->is_descriptor_wrapper()
1766 && !Gogo::is_hidden_name(no->name()))
1767 no->func_value()->descriptor(this->gogo_, no);
1769 return TRAVERSE_CONTINUE;
1772 // If we see a function referenced in any way other than calling it,
1773 // create a descriptor for it.
1776 Create_function_descriptors::expression(Expression** pexpr)
1778 Expression* expr = *pexpr;
1780 Func_expression* fe = expr->func_expression();
1781 if (fe != NULL)
1783 // We would not get here for a call to this function, so this is
1784 // a reference to a function other than calling it. We need a
1785 // descriptor.
1786 if (fe->closure() != NULL)
1787 return TRAVERSE_CONTINUE;
1788 Named_object* no = fe->named_object();
1789 if (no->is_function() && !no->func_value()->is_method())
1790 no->func_value()->descriptor(this->gogo_, no);
1791 else if (no->is_function_declaration()
1792 && !no->func_declaration_value()->type()->is_method()
1793 && !Linemap::is_predeclared_location(no->location()))
1794 no->func_declaration_value()->descriptor(this->gogo_, no);
1795 return TRAVERSE_CONTINUE;
1798 Bound_method_expression* bme = expr->bound_method_expression();
1799 if (bme != NULL)
1801 // We would not get here for a call to this method, so this is a
1802 // method value. We need to create a thunk.
1803 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
1804 bme->function());
1805 return TRAVERSE_CONTINUE;
1808 Interface_field_reference_expression* ifre =
1809 expr->interface_field_reference_expression();
1810 if (ifre != NULL)
1812 // We would not get here for a call to this interface method, so
1813 // this is a method value. We need to create a thunk.
1814 Interface_type* type = ifre->expr()->type()->interface_type();
1815 if (type != NULL)
1816 Interface_field_reference_expression::create_thunk(this->gogo_, type,
1817 ifre->name());
1818 return TRAVERSE_CONTINUE;
1821 Call_expression* ce = expr->call_expression();
1822 if (ce != NULL)
1824 Expression* fn = ce->fn();
1825 if (fn->func_expression() != NULL
1826 || fn->bound_method_expression() != NULL
1827 || fn->interface_field_reference_expression() != NULL)
1829 // Traverse the arguments but not the function.
1830 Expression_list* args = ce->args();
1831 if (args != NULL)
1833 if (args->traverse(this) == TRAVERSE_EXIT)
1834 return TRAVERSE_EXIT;
1836 return TRAVERSE_SKIP_COMPONENTS;
1840 return TRAVERSE_CONTINUE;
1843 // Create function descriptors as needed. We need a function
1844 // descriptor for all exported functions and for all functions that
1845 // are referenced without being called.
1847 void
1848 Gogo::create_function_descriptors()
1850 // Create a function descriptor for any exported function that is
1851 // declared in this package. This is so that we have a descriptor
1852 // for functions written in assembly. Gather the descriptors first
1853 // so that we don't add declarations while looping over them.
1854 std::vector<Named_object*> fndecls;
1855 Bindings* b = this->package_->bindings();
1856 for (Bindings::const_declarations_iterator p = b->begin_declarations();
1857 p != b->end_declarations();
1858 ++p)
1860 Named_object* no = p->second;
1861 if (no->is_function_declaration()
1862 && !no->func_declaration_value()->type()->is_method()
1863 && !Linemap::is_predeclared_location(no->location())
1864 && !Gogo::is_hidden_name(no->name()))
1865 fndecls.push_back(no);
1867 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
1868 p != fndecls.end();
1869 ++p)
1870 (*p)->func_declaration_value()->descriptor(this, *p);
1871 fndecls.clear();
1873 Create_function_descriptors cfd(this);
1874 this->traverse(&cfd);
1877 // Look for interface types to finalize methods of inherited
1878 // interfaces.
1880 class Finalize_methods : public Traverse
1882 public:
1883 Finalize_methods(Gogo* gogo)
1884 : Traverse(traverse_types),
1885 gogo_(gogo)
1889 type(Type*);
1891 private:
1892 Gogo* gogo_;
1895 // Finalize the methods of an interface type.
1898 Finalize_methods::type(Type* t)
1900 // Check the classification so that we don't finalize the methods
1901 // twice for a named interface type.
1902 switch (t->classification())
1904 case Type::TYPE_INTERFACE:
1905 t->interface_type()->finalize_methods();
1906 break;
1908 case Type::TYPE_NAMED:
1910 // We have to finalize the methods of the real type first.
1911 // But if the real type is a struct type, then we only want to
1912 // finalize the methods of the field types, not of the struct
1913 // type itself. We don't want to add methods to the struct,
1914 // since it has a name.
1915 Named_type* nt = t->named_type();
1916 Type* rt = nt->real_type();
1917 if (rt->classification() != Type::TYPE_STRUCT)
1919 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1920 return TRAVERSE_EXIT;
1922 else
1924 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1925 return TRAVERSE_EXIT;
1928 nt->finalize_methods(this->gogo_);
1930 // If this type is defined in a different package, then finalize the
1931 // types of all the methods, since we won't see them otherwise.
1932 if (nt->named_object()->package() != NULL && nt->has_any_methods())
1934 const Methods* methods = nt->methods();
1935 for (Methods::const_iterator p = methods->begin();
1936 p != methods->end();
1937 ++p)
1939 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1940 return TRAVERSE_EXIT;
1944 // Finalize the types of all methods that are declared but not
1945 // defined, since we won't see the declarations otherwise.
1946 if (nt->named_object()->package() == NULL
1947 && nt->local_methods() != NULL)
1949 const Bindings* methods = nt->local_methods();
1950 for (Bindings::const_declarations_iterator p =
1951 methods->begin_declarations();
1952 p != methods->end_declarations();
1953 p++)
1955 if (p->second->is_function_declaration())
1957 Type* mt = p->second->func_declaration_value()->type();
1958 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
1959 return TRAVERSE_EXIT;
1964 return TRAVERSE_SKIP_COMPONENTS;
1967 case Type::TYPE_STRUCT:
1968 // Traverse the field types first in case there is an embedded
1969 // field with methods that the struct should inherit.
1970 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1971 return TRAVERSE_EXIT;
1972 t->struct_type()->finalize_methods(this->gogo_);
1973 return TRAVERSE_SKIP_COMPONENTS;
1975 default:
1976 break;
1979 return TRAVERSE_CONTINUE;
1982 // Finalize method lists and build stub methods for types.
1984 void
1985 Gogo::finalize_methods()
1987 Finalize_methods finalize(this);
1988 this->traverse(&finalize);
1991 // Set types for unspecified variables and constants.
1993 void
1994 Gogo::determine_types()
1996 Bindings* bindings = this->current_bindings();
1997 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1998 p != bindings->end_definitions();
1999 ++p)
2001 if ((*p)->is_function())
2002 (*p)->func_value()->determine_types();
2003 else if ((*p)->is_variable())
2004 (*p)->var_value()->determine_type();
2005 else if ((*p)->is_const())
2006 (*p)->const_value()->determine_type();
2008 // See if a variable requires us to build an initialization
2009 // function. We know that we will see all global variables
2010 // here.
2011 if (!this->need_init_fn_ && (*p)->is_variable())
2013 Variable* variable = (*p)->var_value();
2015 // If this is a global variable which requires runtime
2016 // initialization, we need an initialization function.
2017 if (!variable->is_global())
2019 else if (variable->init() == NULL)
2021 else if (variable->type()->interface_type() != NULL)
2022 this->need_init_fn_ = true;
2023 else if (variable->init()->is_constant())
2025 else if (!variable->init()->is_composite_literal())
2026 this->need_init_fn_ = true;
2027 else if (variable->init()->is_nonconstant_composite_literal())
2028 this->need_init_fn_ = true;
2030 // If this is a global variable which holds a pointer value,
2031 // then we need an initialization function to register it as a
2032 // GC root.
2033 if (variable->is_global() && variable->type()->has_pointer())
2034 this->need_init_fn_ = true;
2038 // Determine the types of constants in packages.
2039 for (Packages::const_iterator p = this->packages_.begin();
2040 p != this->packages_.end();
2041 ++p)
2042 p->second->determine_types();
2045 // Traversal class used for type checking.
2047 class Check_types_traverse : public Traverse
2049 public:
2050 Check_types_traverse(Gogo* gogo)
2051 : Traverse(traverse_variables
2052 | traverse_constants
2053 | traverse_functions
2054 | traverse_statements
2055 | traverse_expressions),
2056 gogo_(gogo)
2060 variable(Named_object*);
2063 constant(Named_object*, bool);
2066 function(Named_object*);
2069 statement(Block*, size_t* pindex, Statement*);
2072 expression(Expression**);
2074 private:
2075 // General IR.
2076 Gogo* gogo_;
2079 // Check that a variable initializer has the right type.
2082 Check_types_traverse::variable(Named_object* named_object)
2084 if (named_object->is_variable())
2086 Variable* var = named_object->var_value();
2088 // Give error if variable type is not defined.
2089 var->type()->base();
2091 Expression* init = var->init();
2092 std::string reason;
2093 if (init != NULL
2094 && !Type::are_assignable(var->type(), init->type(), &reason))
2096 if (reason.empty())
2097 error_at(var->location(), "incompatible type in initialization");
2098 else
2099 error_at(var->location(),
2100 "incompatible type in initialization (%s)",
2101 reason.c_str());
2102 var->clear_init();
2104 else if (!var->is_used()
2105 && !var->is_global()
2106 && !var->is_parameter()
2107 && !var->is_receiver()
2108 && !var->type()->is_error()
2109 && (init == NULL || !init->is_error_expression())
2110 && !Lex::is_invalid_identifier(named_object->name()))
2111 error_at(var->location(), "%qs declared and not used",
2112 named_object->message_name().c_str());
2114 return TRAVERSE_CONTINUE;
2117 // Check that a constant initializer has the right type.
2120 Check_types_traverse::constant(Named_object* named_object, bool)
2122 Named_constant* constant = named_object->const_value();
2123 Type* ctype = constant->type();
2124 if (ctype->integer_type() == NULL
2125 && ctype->float_type() == NULL
2126 && ctype->complex_type() == NULL
2127 && !ctype->is_boolean_type()
2128 && !ctype->is_string_type())
2130 if (ctype->is_nil_type())
2131 error_at(constant->location(), "const initializer cannot be nil");
2132 else if (!ctype->is_error())
2133 error_at(constant->location(), "invalid constant type");
2134 constant->set_error();
2136 else if (!constant->expr()->is_constant())
2138 error_at(constant->expr()->location(), "expression is not constant");
2139 constant->set_error();
2141 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
2142 NULL))
2144 error_at(constant->location(),
2145 "initialization expression has wrong type");
2146 constant->set_error();
2148 return TRAVERSE_CONTINUE;
2151 // There are no types to check in a function, but this is where we
2152 // issue warnings about labels which are defined but not referenced.
2155 Check_types_traverse::function(Named_object* no)
2157 no->func_value()->check_labels();
2158 return TRAVERSE_CONTINUE;
2161 // Check that types are valid in a statement.
2164 Check_types_traverse::statement(Block*, size_t*, Statement* s)
2166 s->check_types(this->gogo_);
2167 return TRAVERSE_CONTINUE;
2170 // Check that types are valid in an expression.
2173 Check_types_traverse::expression(Expression** expr)
2175 (*expr)->check_types(this->gogo_);
2176 return TRAVERSE_CONTINUE;
2179 // Check that types are valid.
2181 void
2182 Gogo::check_types()
2184 Check_types_traverse traverse(this);
2185 this->traverse(&traverse);
2188 // Check the types in a single block.
2190 void
2191 Gogo::check_types_in_block(Block* block)
2193 Check_types_traverse traverse(this);
2194 block->traverse(&traverse);
2197 // A traversal class used to find a single shortcut operator within an
2198 // expression.
2200 class Find_shortcut : public Traverse
2202 public:
2203 Find_shortcut()
2204 : Traverse(traverse_blocks
2205 | traverse_statements
2206 | traverse_expressions),
2207 found_(NULL)
2210 // A pointer to the expression which was found, or NULL if none was
2211 // found.
2212 Expression**
2213 found() const
2214 { return this->found_; }
2216 protected:
2218 block(Block*)
2219 { return TRAVERSE_SKIP_COMPONENTS; }
2222 statement(Block*, size_t*, Statement*)
2223 { return TRAVERSE_SKIP_COMPONENTS; }
2226 expression(Expression**);
2228 private:
2229 Expression** found_;
2232 // Find a shortcut expression.
2235 Find_shortcut::expression(Expression** pexpr)
2237 Expression* expr = *pexpr;
2238 Binary_expression* be = expr->binary_expression();
2239 if (be == NULL)
2240 return TRAVERSE_CONTINUE;
2241 Operator op = be->op();
2242 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
2243 return TRAVERSE_CONTINUE;
2244 go_assert(this->found_ == NULL);
2245 this->found_ = pexpr;
2246 return TRAVERSE_EXIT;
2249 // A traversal class used to turn shortcut operators into explicit if
2250 // statements.
2252 class Shortcuts : public Traverse
2254 public:
2255 Shortcuts(Gogo* gogo)
2256 : Traverse(traverse_variables
2257 | traverse_statements),
2258 gogo_(gogo)
2261 protected:
2263 variable(Named_object*);
2266 statement(Block*, size_t*, Statement*);
2268 private:
2269 // Convert a shortcut operator.
2270 Statement*
2271 convert_shortcut(Block* enclosing, Expression** pshortcut);
2273 // The IR.
2274 Gogo* gogo_;
2277 // Remove shortcut operators in a single statement.
2280 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
2282 // FIXME: This approach doesn't work for switch statements, because
2283 // we add the new statements before the whole switch when we need to
2284 // instead add them just before the switch expression. The right
2285 // fix is probably to lower switch statements with nonconstant cases
2286 // to a series of conditionals.
2287 if (s->switch_statement() != NULL)
2288 return TRAVERSE_CONTINUE;
2290 while (true)
2292 Find_shortcut find_shortcut;
2294 // If S is a variable declaration, then ordinary traversal won't
2295 // do anything. We want to explicitly traverse the
2296 // initialization expression if there is one.
2297 Variable_declaration_statement* vds = s->variable_declaration_statement();
2298 Expression* init = NULL;
2299 if (vds == NULL)
2300 s->traverse_contents(&find_shortcut);
2301 else
2303 init = vds->var()->var_value()->init();
2304 if (init == NULL)
2305 return TRAVERSE_CONTINUE;
2306 init->traverse(&init, &find_shortcut);
2308 Expression** pshortcut = find_shortcut.found();
2309 if (pshortcut == NULL)
2310 return TRAVERSE_CONTINUE;
2312 Statement* snew = this->convert_shortcut(block, pshortcut);
2313 block->insert_statement_before(*pindex, snew);
2314 ++*pindex;
2316 if (pshortcut == &init)
2317 vds->var()->var_value()->set_init(init);
2321 // Remove shortcut operators in the initializer of a global variable.
2324 Shortcuts::variable(Named_object* no)
2326 if (no->is_result_variable())
2327 return TRAVERSE_CONTINUE;
2328 Variable* var = no->var_value();
2329 Expression* init = var->init();
2330 if (!var->is_global() || init == NULL)
2331 return TRAVERSE_CONTINUE;
2333 while (true)
2335 Find_shortcut find_shortcut;
2336 init->traverse(&init, &find_shortcut);
2337 Expression** pshortcut = find_shortcut.found();
2338 if (pshortcut == NULL)
2339 return TRAVERSE_CONTINUE;
2341 Statement* snew = this->convert_shortcut(NULL, pshortcut);
2342 var->add_preinit_statement(this->gogo_, snew);
2343 if (pshortcut == &init)
2344 var->set_init(init);
2348 // Given an expression which uses a shortcut operator, return a
2349 // statement which implements it, and update *PSHORTCUT accordingly.
2351 Statement*
2352 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2354 Binary_expression* shortcut = (*pshortcut)->binary_expression();
2355 Expression* left = shortcut->left();
2356 Expression* right = shortcut->right();
2357 Location loc = shortcut->location();
2359 Block* retblock = new Block(enclosing, loc);
2360 retblock->set_end_location(loc);
2362 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
2363 left, loc);
2364 retblock->add_statement(ts);
2366 Block* block = new Block(retblock, loc);
2367 block->set_end_location(loc);
2368 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2369 Statement* assign = Statement::make_assignment(tmpref, right, loc);
2370 block->add_statement(assign);
2372 Expression* cond = Expression::make_temporary_reference(ts, loc);
2373 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2374 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2376 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2377 loc);
2378 retblock->add_statement(if_statement);
2380 *pshortcut = Expression::make_temporary_reference(ts, loc);
2382 delete shortcut;
2384 // Now convert any shortcut operators in LEFT and RIGHT.
2385 Shortcuts shortcuts(this->gogo_);
2386 retblock->traverse(&shortcuts);
2388 return Statement::make_block_statement(retblock, loc);
2391 // Turn shortcut operators into explicit if statements. Doing this
2392 // considerably simplifies the order of evaluation rules.
2394 void
2395 Gogo::remove_shortcuts()
2397 Shortcuts shortcuts(this);
2398 this->traverse(&shortcuts);
2401 // A traversal class which finds all the expressions which must be
2402 // evaluated in order within a statement or larger expression. This
2403 // is used to implement the rules about order of evaluation.
2405 class Find_eval_ordering : public Traverse
2407 private:
2408 typedef std::vector<Expression**> Expression_pointers;
2410 public:
2411 Find_eval_ordering()
2412 : Traverse(traverse_blocks
2413 | traverse_statements
2414 | traverse_expressions),
2415 exprs_()
2418 size_t
2419 size() const
2420 { return this->exprs_.size(); }
2422 typedef Expression_pointers::const_iterator const_iterator;
2424 const_iterator
2425 begin() const
2426 { return this->exprs_.begin(); }
2428 const_iterator
2429 end() const
2430 { return this->exprs_.end(); }
2432 protected:
2434 block(Block*)
2435 { return TRAVERSE_SKIP_COMPONENTS; }
2438 statement(Block*, size_t*, Statement*)
2439 { return TRAVERSE_SKIP_COMPONENTS; }
2442 expression(Expression**);
2444 private:
2445 // A list of pointers to expressions with side-effects.
2446 Expression_pointers exprs_;
2449 // If an expression must be evaluated in order, put it on the list.
2452 Find_eval_ordering::expression(Expression** expression_pointer)
2454 // We have to look at subexpressions before this one.
2455 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2456 return TRAVERSE_EXIT;
2457 if ((*expression_pointer)->must_eval_in_order())
2458 this->exprs_.push_back(expression_pointer);
2459 return TRAVERSE_SKIP_COMPONENTS;
2462 // A traversal class for ordering evaluations.
2464 class Order_eval : public Traverse
2466 public:
2467 Order_eval(Gogo* gogo)
2468 : Traverse(traverse_variables
2469 | traverse_statements),
2470 gogo_(gogo)
2474 variable(Named_object*);
2477 statement(Block*, size_t*, Statement*);
2479 private:
2480 // The IR.
2481 Gogo* gogo_;
2484 // Implement the order of evaluation rules for a statement.
2487 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2489 // FIXME: This approach doesn't work for switch statements, because
2490 // we add the new statements before the whole switch when we need to
2491 // instead add them just before the switch expression. The right
2492 // fix is probably to lower switch statements with nonconstant cases
2493 // to a series of conditionals.
2494 if (s->switch_statement() != NULL)
2495 return TRAVERSE_CONTINUE;
2497 Find_eval_ordering find_eval_ordering;
2499 // If S is a variable declaration, then ordinary traversal won't do
2500 // anything. We want to explicitly traverse the initialization
2501 // expression if there is one.
2502 Variable_declaration_statement* vds = s->variable_declaration_statement();
2503 Expression* init = NULL;
2504 Expression* orig_init = NULL;
2505 if (vds == NULL)
2506 s->traverse_contents(&find_eval_ordering);
2507 else
2509 init = vds->var()->var_value()->init();
2510 if (init == NULL)
2511 return TRAVERSE_CONTINUE;
2512 orig_init = init;
2514 // It might seem that this could be
2515 // init->traverse_subexpressions. Unfortunately that can fail
2516 // in a case like
2517 // var err os.Error
2518 // newvar, err := call(arg())
2519 // Here newvar will have an init of call result 0 of
2520 // call(arg()). If we only traverse subexpressions, we will
2521 // only find arg(), and we won't bother to move anything out.
2522 // Then we get to the assignment to err, we will traverse the
2523 // whole statement, and this time we will find both call() and
2524 // arg(), and so we will move them out. This will cause them to
2525 // be put into temporary variables before the assignment to err
2526 // but after the declaration of newvar. To avoid that problem,
2527 // we traverse the entire expression here.
2528 Expression::traverse(&init, &find_eval_ordering);
2531 size_t c = find_eval_ordering.size();
2532 if (c == 0)
2533 return TRAVERSE_CONTINUE;
2535 // If there is only one expression with a side-effect, we can
2536 // usually leave it in place. However, for an assignment statement,
2537 // we need to evaluate an expression on the right hand side before
2538 // we evaluate any index expression on the left hand side, so for
2539 // that case we always move the expression. Otherwise we mishandle
2540 // m[0] = len(m) where m is a map.
2541 if (c == 1 && s->classification() != Statement::STATEMENT_ASSIGNMENT)
2542 return TRAVERSE_CONTINUE;
2544 bool is_thunk = s->thunk_statement() != NULL;
2545 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2546 p != find_eval_ordering.end();
2547 ++p)
2549 Expression** pexpr = *p;
2551 // The last expression in a thunk will be the call passed to go
2552 // or defer, which we must not evaluate early.
2553 if (is_thunk && p + 1 == find_eval_ordering.end())
2554 break;
2556 Location loc = (*pexpr)->location();
2557 Statement* s;
2558 if ((*pexpr)->call_expression() == NULL
2559 || (*pexpr)->call_expression()->result_count() < 2)
2561 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2562 loc);
2563 s = ts;
2564 *pexpr = Expression::make_temporary_reference(ts, loc);
2566 else
2568 // A call expression which returns multiple results needs to
2569 // be handled specially. We can't create a temporary
2570 // because there is no type to give it. Any actual uses of
2571 // the values will be done via Call_result_expressions.
2572 s = Statement::make_statement(*pexpr, true);
2575 block->insert_statement_before(*pindex, s);
2576 ++*pindex;
2579 if (init != orig_init)
2580 vds->var()->var_value()->set_init(init);
2582 return TRAVERSE_CONTINUE;
2585 // Implement the order of evaluation rules for the initializer of a
2586 // global variable.
2589 Order_eval::variable(Named_object* no)
2591 if (no->is_result_variable())
2592 return TRAVERSE_CONTINUE;
2593 Variable* var = no->var_value();
2594 Expression* init = var->init();
2595 if (!var->is_global() || init == NULL)
2596 return TRAVERSE_CONTINUE;
2598 Find_eval_ordering find_eval_ordering;
2599 Expression::traverse(&init, &find_eval_ordering);
2601 if (find_eval_ordering.size() <= 1)
2603 // If there is only one expression with a side-effect, we can
2604 // leave it in place.
2605 return TRAVERSE_SKIP_COMPONENTS;
2608 Expression* orig_init = init;
2610 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2611 p != find_eval_ordering.end();
2612 ++p)
2614 Expression** pexpr = *p;
2615 Location loc = (*pexpr)->location();
2616 Statement* s;
2617 if ((*pexpr)->call_expression() == NULL
2618 || (*pexpr)->call_expression()->result_count() < 2)
2620 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2621 loc);
2622 s = ts;
2623 *pexpr = Expression::make_temporary_reference(ts, loc);
2625 else
2627 // A call expression which returns multiple results needs to
2628 // be handled specially.
2629 s = Statement::make_statement(*pexpr, true);
2631 var->add_preinit_statement(this->gogo_, s);
2634 if (init != orig_init)
2635 var->set_init(init);
2637 return TRAVERSE_SKIP_COMPONENTS;
2640 // Use temporary variables to implement the order of evaluation rules.
2642 void
2643 Gogo::order_evaluations()
2645 Order_eval order_eval(this);
2646 this->traverse(&order_eval);
2649 // Traversal to convert calls to the predeclared recover function to
2650 // pass in an argument indicating whether it can recover from a panic
2651 // or not.
2653 class Convert_recover : public Traverse
2655 public:
2656 Convert_recover(Named_object* arg)
2657 : Traverse(traverse_expressions),
2658 arg_(arg)
2661 protected:
2663 expression(Expression**);
2665 private:
2666 // The argument to pass to the function.
2667 Named_object* arg_;
2670 // Convert calls to recover.
2673 Convert_recover::expression(Expression** pp)
2675 Call_expression* ce = (*pp)->call_expression();
2676 if (ce != NULL && ce->is_recover_call())
2677 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2678 ce->location()));
2679 return TRAVERSE_CONTINUE;
2682 // Traversal for build_recover_thunks.
2684 class Build_recover_thunks : public Traverse
2686 public:
2687 Build_recover_thunks(Gogo* gogo)
2688 : Traverse(traverse_functions),
2689 gogo_(gogo)
2693 function(Named_object*);
2695 private:
2696 Expression*
2697 can_recover_arg(Location);
2699 // General IR.
2700 Gogo* gogo_;
2703 // If this function calls recover, turn it into a thunk.
2706 Build_recover_thunks::function(Named_object* orig_no)
2708 Function* orig_func = orig_no->func_value();
2709 if (!orig_func->calls_recover()
2710 || orig_func->is_recover_thunk()
2711 || orig_func->has_recover_thunk())
2712 return TRAVERSE_CONTINUE;
2714 Gogo* gogo = this->gogo_;
2715 Location location = orig_func->location();
2717 static int count;
2718 char buf[50];
2720 Function_type* orig_fntype = orig_func->type();
2721 Typed_identifier_list* new_params = new Typed_identifier_list();
2722 std::string receiver_name;
2723 if (orig_fntype->is_method())
2725 const Typed_identifier* receiver = orig_fntype->receiver();
2726 snprintf(buf, sizeof buf, "rt.%u", count);
2727 ++count;
2728 receiver_name = buf;
2729 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2730 receiver->location()));
2732 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2733 if (orig_params != NULL && !orig_params->empty())
2735 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2736 p != orig_params->end();
2737 ++p)
2739 snprintf(buf, sizeof buf, "pt.%u", count);
2740 ++count;
2741 new_params->push_back(Typed_identifier(buf, p->type(),
2742 p->location()));
2745 snprintf(buf, sizeof buf, "pr.%u", count);
2746 ++count;
2747 std::string can_recover_name = buf;
2748 new_params->push_back(Typed_identifier(can_recover_name,
2749 Type::lookup_bool_type(),
2750 orig_fntype->location()));
2752 const Typed_identifier_list* orig_results = orig_fntype->results();
2753 Typed_identifier_list* new_results;
2754 if (orig_results == NULL || orig_results->empty())
2755 new_results = NULL;
2756 else
2758 new_results = new Typed_identifier_list();
2759 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2760 p != orig_results->end();
2761 ++p)
2762 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2765 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2766 new_results,
2767 orig_fntype->location());
2768 if (orig_fntype->is_varargs())
2769 new_fntype->set_is_varargs();
2771 std::string name = orig_no->name() + "$recover";
2772 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2773 location);
2774 Function *new_func = new_no->func_value();
2775 if (orig_func->enclosing() != NULL)
2776 new_func->set_enclosing(orig_func->enclosing());
2778 // We build the code for the original function attached to the new
2779 // function, and then swap the original and new function bodies.
2780 // This means that existing references to the original function will
2781 // then refer to the new function. That makes this code a little
2782 // confusing, in that the reference to NEW_NO really refers to the
2783 // other function, not the one we are building.
2785 Expression* closure = NULL;
2786 if (orig_func->needs_closure())
2788 // For the new function we are creating, declare a new parameter
2789 // variable NEW_CLOSURE_NO and set it to be the closure variable
2790 // of the function. This will be set to the closure value
2791 // passed in by the caller. Then pass a reference to this
2792 // variable as the closure value when calling the original
2793 // function. In other words, simply pass the closure value
2794 // through the thunk we are creating.
2795 Named_object* orig_closure_no = orig_func->closure_var();
2796 Variable* orig_closure_var = orig_closure_no->var_value();
2797 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2798 true, false, location);
2799 snprintf(buf, sizeof buf, "closure.%u", count);
2800 ++count;
2801 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2802 new_var);
2803 new_func->set_closure_var(new_closure_no);
2804 closure = Expression::make_var_reference(new_closure_no, location);
2807 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2809 Expression_list* args = new Expression_list();
2810 if (new_params != NULL)
2812 // Note that we skip the last parameter, which is the boolean
2813 // indicating whether recover can succed.
2814 for (Typed_identifier_list::const_iterator p = new_params->begin();
2815 p + 1 != new_params->end();
2816 ++p)
2818 Named_object* p_no = gogo->lookup(p->name(), NULL);
2819 go_assert(p_no != NULL
2820 && p_no->is_variable()
2821 && p_no->var_value()->is_parameter());
2822 args->push_back(Expression::make_var_reference(p_no, location));
2825 args->push_back(this->can_recover_arg(location));
2827 gogo->start_block(location);
2829 Call_expression* call = Expression::make_call(fn, args, false, location);
2831 // Any varargs call has already been lowered.
2832 call->set_varargs_are_lowered();
2834 Statement* s = Statement::make_return_from_call(call, location);
2835 s->determine_types();
2836 gogo->add_statement(s);
2838 Block* b = gogo->finish_block(location);
2840 gogo->add_block(b, location);
2842 // Lower the call in case it returns multiple results.
2843 gogo->lower_block(new_no, b);
2845 gogo->finish_function(location);
2847 // Swap the function bodies and types.
2848 new_func->swap_for_recover(orig_func);
2849 orig_func->set_is_recover_thunk();
2850 new_func->set_calls_recover();
2851 new_func->set_has_recover_thunk();
2853 Bindings* orig_bindings = orig_func->block()->bindings();
2854 Bindings* new_bindings = new_func->block()->bindings();
2855 if (orig_fntype->is_method())
2857 // We changed the receiver to be a regular parameter. We have
2858 // to update the binding accordingly in both functions.
2859 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2860 go_assert(orig_rec_no != NULL
2861 && orig_rec_no->is_variable()
2862 && !orig_rec_no->var_value()->is_receiver());
2863 orig_rec_no->var_value()->set_is_receiver();
2865 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2866 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2867 if (new_rec_no == NULL)
2868 go_assert(saw_errors());
2869 else
2871 go_assert(new_rec_no->is_variable()
2872 && new_rec_no->var_value()->is_receiver());
2873 new_rec_no->var_value()->set_is_not_receiver();
2877 // Because we flipped blocks but not types, the can_recover
2878 // parameter appears in the (now) old bindings as a parameter.
2879 // Change it to a local variable, whereupon it will be discarded.
2880 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2881 go_assert(can_recover_no != NULL
2882 && can_recover_no->is_variable()
2883 && can_recover_no->var_value()->is_parameter());
2884 orig_bindings->remove_binding(can_recover_no);
2886 // Add the can_recover argument to the (now) new bindings, and
2887 // attach it to any recover statements.
2888 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2889 false, true, false, location);
2890 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2891 can_recover_var);
2892 Convert_recover convert_recover(can_recover_no);
2893 new_func->traverse(&convert_recover);
2895 // Update the function pointers in any named results.
2896 new_func->update_result_variables();
2897 orig_func->update_result_variables();
2899 return TRAVERSE_CONTINUE;
2902 // Return the expression to pass for the .can_recover parameter to the
2903 // new function. This indicates whether a call to recover may return
2904 // non-nil. The expression is
2905 // __go_can_recover(__builtin_return_address()).
2907 Expression*
2908 Build_recover_thunks::can_recover_arg(Location location)
2910 static Named_object* builtin_return_address;
2911 if (builtin_return_address == NULL)
2913 const Location bloc = Linemap::predeclared_location();
2915 Typed_identifier_list* param_types = new Typed_identifier_list();
2916 Type* uint_type = Type::lookup_integer_type("uint");
2917 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2919 Typed_identifier_list* return_types = new Typed_identifier_list();
2920 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2921 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2923 Function_type* fntype = Type::make_function_type(NULL, param_types,
2924 return_types, bloc);
2925 builtin_return_address =
2926 Named_object::make_function_declaration("__builtin_return_address",
2927 NULL, fntype, bloc);
2928 const char* n = "__builtin_return_address";
2929 builtin_return_address->func_declaration_value()->set_asm_name(n);
2932 static Named_object* can_recover;
2933 if (can_recover == NULL)
2935 const Location bloc = Linemap::predeclared_location();
2936 Typed_identifier_list* param_types = new Typed_identifier_list();
2937 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2938 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2939 Type* boolean_type = Type::lookup_bool_type();
2940 Typed_identifier_list* results = new Typed_identifier_list();
2941 results->push_back(Typed_identifier("", boolean_type, bloc));
2942 Function_type* fntype = Type::make_function_type(NULL, param_types,
2943 results, bloc);
2944 can_recover = Named_object::make_function_declaration("__go_can_recover",
2945 NULL, fntype,
2946 bloc);
2947 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2950 Expression* fn = Expression::make_func_reference(builtin_return_address,
2951 NULL, location);
2953 mpz_t zval;
2954 mpz_init_set_ui(zval, 0UL);
2955 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2956 mpz_clear(zval);
2957 Expression_list *args = new Expression_list();
2958 args->push_back(zexpr);
2960 Expression* call = Expression::make_call(fn, args, false, location);
2962 args = new Expression_list();
2963 args->push_back(call);
2965 fn = Expression::make_func_reference(can_recover, NULL, location);
2966 return Expression::make_call(fn, args, false, location);
2969 // Build thunks for functions which call recover. We build a new
2970 // function with an extra parameter, which is whether a call to
2971 // recover can succeed. We then move the body of this function to
2972 // that one. We then turn this function into a thunk which calls the
2973 // new one, passing the value of
2974 // __go_can_recover(__builtin_return_address()). The function will be
2975 // marked as not splitting the stack. This will cooperate with the
2976 // implementation of defer to make recover do the right thing.
2978 void
2979 Gogo::build_recover_thunks()
2981 Build_recover_thunks build_recover_thunks(this);
2982 this->traverse(&build_recover_thunks);
2985 // Look for named types to see whether we need to create an interface
2986 // method table.
2988 class Build_method_tables : public Traverse
2990 public:
2991 Build_method_tables(Gogo* gogo,
2992 const std::vector<Interface_type*>& interfaces)
2993 : Traverse(traverse_types),
2994 gogo_(gogo), interfaces_(interfaces)
2998 type(Type*);
3000 private:
3001 // The IR.
3002 Gogo* gogo_;
3003 // A list of locally defined interfaces which have hidden methods.
3004 const std::vector<Interface_type*>& interfaces_;
3007 // Build all required interface method tables for types. We need to
3008 // ensure that we have an interface method table for every interface
3009 // which has a hidden method, for every named type which implements
3010 // that interface. Normally we can just build interface method tables
3011 // as we need them. However, in some cases we can require an
3012 // interface method table for an interface defined in a different
3013 // package for a type defined in that package. If that interface and
3014 // type both use a hidden method, that is OK. However, we will not be
3015 // able to build that interface method table when we need it, because
3016 // the type's hidden method will be static. So we have to build it
3017 // here, and just refer it from other packages as needed.
3019 void
3020 Gogo::build_interface_method_tables()
3022 if (saw_errors())
3023 return;
3025 std::vector<Interface_type*> hidden_interfaces;
3026 hidden_interfaces.reserve(this->interface_types_.size());
3027 for (std::vector<Interface_type*>::const_iterator pi =
3028 this->interface_types_.begin();
3029 pi != this->interface_types_.end();
3030 ++pi)
3032 const Typed_identifier_list* methods = (*pi)->methods();
3033 if (methods == NULL)
3034 continue;
3035 for (Typed_identifier_list::const_iterator pm = methods->begin();
3036 pm != methods->end();
3037 ++pm)
3039 if (Gogo::is_hidden_name(pm->name()))
3041 hidden_interfaces.push_back(*pi);
3042 break;
3047 if (!hidden_interfaces.empty())
3049 // Now traverse the tree looking for all named types.
3050 Build_method_tables bmt(this, hidden_interfaces);
3051 this->traverse(&bmt);
3054 // We no longer need the list of interfaces.
3056 this->interface_types_.clear();
3059 // This is called for each type. For a named type, for each of the
3060 // interfaces with hidden methods that it implements, create the
3061 // method table.
3064 Build_method_tables::type(Type* type)
3066 Named_type* nt = type->named_type();
3067 Struct_type* st = type->struct_type();
3068 if (nt != NULL || st != NULL)
3070 for (std::vector<Interface_type*>::const_iterator p =
3071 this->interfaces_.begin();
3072 p != this->interfaces_.end();
3073 ++p)
3075 // We ask whether a pointer to the named type implements the
3076 // interface, because a pointer can implement more methods
3077 // than a value.
3078 if (nt != NULL)
3080 if ((*p)->implements_interface(Type::make_pointer_type(nt),
3081 NULL))
3083 nt->interface_method_table(this->gogo_, *p, false);
3084 nt->interface_method_table(this->gogo_, *p, true);
3087 else
3089 if ((*p)->implements_interface(Type::make_pointer_type(st),
3090 NULL))
3092 st->interface_method_table(this->gogo_, *p, false);
3093 st->interface_method_table(this->gogo_, *p, true);
3098 return TRAVERSE_CONTINUE;
3101 // Traversal class used to check for return statements.
3103 class Check_return_statements_traverse : public Traverse
3105 public:
3106 Check_return_statements_traverse()
3107 : Traverse(traverse_functions)
3111 function(Named_object*);
3114 // Check that a function has a return statement if it needs one.
3117 Check_return_statements_traverse::function(Named_object* no)
3119 Function* func = no->func_value();
3120 const Function_type* fntype = func->type();
3121 const Typed_identifier_list* results = fntype->results();
3123 // We only need a return statement if there is a return value.
3124 if (results == NULL || results->empty())
3125 return TRAVERSE_CONTINUE;
3127 if (func->block()->may_fall_through())
3128 error_at(func->location(), "control reaches end of non-void function");
3130 return TRAVERSE_CONTINUE;
3133 // Check return statements.
3135 void
3136 Gogo::check_return_statements()
3138 Check_return_statements_traverse traverse;
3139 this->traverse(&traverse);
3142 // Work out the package priority. It is one more than the maximum
3143 // priority of an imported package.
3146 Gogo::package_priority() const
3148 int priority = 0;
3149 for (Packages::const_iterator p = this->packages_.begin();
3150 p != this->packages_.end();
3151 ++p)
3152 if (p->second->priority() > priority)
3153 priority = p->second->priority();
3154 return priority + 1;
3157 // Export identifiers as requested.
3159 void
3160 Gogo::do_exports()
3162 // For now we always stream to a section. Later we may want to
3163 // support streaming to a separate file.
3164 Stream_to_section stream;
3166 Export exp(&stream);
3167 exp.register_builtin_types(this);
3168 exp.export_globals(this->package_name(),
3169 this->pkgpath(),
3170 this->package_priority(),
3171 this->imports_,
3172 (this->need_init_fn_ && !this->is_main_package()
3173 ? this->get_init_fn_name()
3174 : ""),
3175 this->imported_init_fns_,
3176 this->package_->bindings());
3179 // Find the blocks in order to convert named types defined in blocks.
3181 class Convert_named_types : public Traverse
3183 public:
3184 Convert_named_types(Gogo* gogo)
3185 : Traverse(traverse_blocks),
3186 gogo_(gogo)
3189 protected:
3191 block(Block* block);
3193 private:
3194 Gogo* gogo_;
3198 Convert_named_types::block(Block* block)
3200 this->gogo_->convert_named_types_in_bindings(block->bindings());
3201 return TRAVERSE_CONTINUE;
3204 // Convert all named types to the backend representation. Since named
3205 // types can refer to other types, this needs to be done in the right
3206 // sequence, which is handled by Named_type::convert. Here we arrange
3207 // to call that for each named type.
3209 void
3210 Gogo::convert_named_types()
3212 this->convert_named_types_in_bindings(this->globals_);
3213 for (Packages::iterator p = this->packages_.begin();
3214 p != this->packages_.end();
3215 ++p)
3217 Package* package = p->second;
3218 this->convert_named_types_in_bindings(package->bindings());
3221 Convert_named_types cnt(this);
3222 this->traverse(&cnt);
3224 // Make all the builtin named types used for type descriptors, and
3225 // then convert them. They will only be written out if they are
3226 // needed.
3227 Type::make_type_descriptor_type();
3228 Type::make_type_descriptor_ptr_type();
3229 Function_type::make_function_type_descriptor_type();
3230 Pointer_type::make_pointer_type_descriptor_type();
3231 Struct_type::make_struct_type_descriptor_type();
3232 Array_type::make_array_type_descriptor_type();
3233 Array_type::make_slice_type_descriptor_type();
3234 Map_type::make_map_type_descriptor_type();
3235 Map_type::make_map_descriptor_type();
3236 Channel_type::make_chan_type_descriptor_type();
3237 Interface_type::make_interface_type_descriptor_type();
3238 Expression::make_func_descriptor_type();
3239 Type::convert_builtin_named_types(this);
3241 Runtime::convert_types(this);
3243 this->named_types_are_converted_ = true;
3246 // Convert all names types in a set of bindings.
3248 void
3249 Gogo::convert_named_types_in_bindings(Bindings* bindings)
3251 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3252 p != bindings->end_definitions();
3253 ++p)
3255 if ((*p)->is_type())
3256 (*p)->type_value()->convert(this);
3260 // Class Function.
3262 Function::Function(Function_type* type, Function* enclosing, Block* block,
3263 Location location)
3264 : type_(type), enclosing_(enclosing), results_(NULL),
3265 closure_var_(NULL), block_(block), location_(location), labels_(),
3266 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
3267 is_sink_(false), results_are_named_(false), nointerface_(false),
3268 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
3269 in_unique_section_(false), is_descriptor_wrapper_(false)
3273 // Create the named result variables.
3275 void
3276 Function::create_result_variables(Gogo* gogo)
3278 const Typed_identifier_list* results = this->type_->results();
3279 if (results == NULL || results->empty())
3280 return;
3282 if (!results->front().name().empty())
3283 this->results_are_named_ = true;
3285 this->results_ = new Results();
3286 this->results_->reserve(results->size());
3288 Block* block = this->block_;
3289 int index = 0;
3290 for (Typed_identifier_list::const_iterator p = results->begin();
3291 p != results->end();
3292 ++p, ++index)
3294 std::string name = p->name();
3295 if (name.empty() || Gogo::is_sink_name(name))
3297 static int result_counter;
3298 char buf[100];
3299 snprintf(buf, sizeof buf, "$ret%d", result_counter);
3300 ++result_counter;
3301 name = gogo->pack_hidden_name(buf, false);
3303 Result_variable* result = new Result_variable(p->type(), this, index,
3304 p->location());
3305 Named_object* no = block->bindings()->add_result_variable(name, result);
3306 if (no->is_result_variable())
3307 this->results_->push_back(no);
3308 else
3310 static int dummy_result_count;
3311 char buf[100];
3312 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
3313 ++dummy_result_count;
3314 name = gogo->pack_hidden_name(buf, false);
3315 no = block->bindings()->add_result_variable(name, result);
3316 go_assert(no->is_result_variable());
3317 this->results_->push_back(no);
3322 // Update the named result variables when cloning a function which
3323 // calls recover.
3325 void
3326 Function::update_result_variables()
3328 if (this->results_ == NULL)
3329 return;
3331 for (Results::iterator p = this->results_->begin();
3332 p != this->results_->end();
3333 ++p)
3334 (*p)->result_var_value()->set_function(this);
3337 // Return the closure variable, creating it if necessary.
3339 Named_object*
3340 Function::closure_var()
3342 if (this->closure_var_ == NULL)
3344 go_assert(this->descriptor_ == NULL);
3345 // We don't know the type of the variable yet. We add fields as
3346 // we find them.
3347 Location loc = this->type_->location();
3348 Struct_field_list* sfl = new Struct_field_list;
3349 Type* struct_type = Type::make_struct_type(sfl, loc);
3350 Variable* var = new Variable(Type::make_pointer_type(struct_type),
3351 NULL, false, true, false, loc);
3352 var->set_is_used();
3353 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
3354 // Note that the new variable is not in any binding contour.
3356 return this->closure_var_;
3359 // Set the type of the closure variable.
3361 void
3362 Function::set_closure_type()
3364 if (this->closure_var_ == NULL)
3365 return;
3366 Named_object* closure = this->closure_var_;
3367 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3369 // The first field of a closure is always a pointer to the function
3370 // code.
3371 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
3372 st->push_field(Struct_field(Typed_identifier(".$f", voidptr_type,
3373 this->location_)));
3375 unsigned int index = 0;
3376 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3377 p != this->closure_fields_.end();
3378 ++p, ++index)
3380 Named_object* no = p->first;
3381 char buf[20];
3382 snprintf(buf, sizeof buf, "%u", index);
3383 std::string n = no->name() + buf;
3384 Type* var_type;
3385 if (no->is_variable())
3386 var_type = no->var_value()->type();
3387 else
3388 var_type = no->result_var_value()->type();
3389 Type* field_type = Type::make_pointer_type(var_type);
3390 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3394 // Return whether this function is a method.
3396 bool
3397 Function::is_method() const
3399 return this->type_->is_method();
3402 // Add a label definition.
3404 Label*
3405 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3406 Location location)
3408 Label* lnull = NULL;
3409 std::pair<Labels::iterator, bool> ins =
3410 this->labels_.insert(std::make_pair(label_name, lnull));
3411 Label* label;
3412 if (ins.second)
3414 // This is a new label.
3415 label = new Label(label_name);
3416 ins.first->second = label;
3418 else
3420 // The label was already in the hash table.
3421 label = ins.first->second;
3422 if (label->is_defined())
3424 error_at(location, "label %qs already defined",
3425 Gogo::message_name(label_name).c_str());
3426 inform(label->location(), "previous definition of %qs was here",
3427 Gogo::message_name(label_name).c_str());
3428 return new Label(label_name);
3432 label->define(location, gogo->bindings_snapshot(location));
3434 // Issue any errors appropriate for any previous goto's to this
3435 // label.
3436 const std::vector<Bindings_snapshot*>& refs(label->refs());
3437 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3438 p != refs.end();
3439 ++p)
3440 (*p)->check_goto_to(gogo->current_block());
3441 label->clear_refs();
3443 return label;
3446 // Add a reference to a label.
3448 Label*
3449 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3450 Location location, bool issue_goto_errors)
3452 Label* lnull = NULL;
3453 std::pair<Labels::iterator, bool> ins =
3454 this->labels_.insert(std::make_pair(label_name, lnull));
3455 Label* label;
3456 if (!ins.second)
3458 // The label was already in the hash table.
3459 label = ins.first->second;
3461 else
3463 go_assert(ins.first->second == NULL);
3464 label = new Label(label_name);
3465 ins.first->second = label;
3468 label->set_is_used();
3470 if (issue_goto_errors)
3472 Bindings_snapshot* snapshot = label->snapshot();
3473 if (snapshot != NULL)
3474 snapshot->check_goto_from(gogo->current_block(), location);
3475 else
3476 label->add_snapshot_ref(gogo->bindings_snapshot(location));
3479 return label;
3482 // Warn about labels that are defined but not used.
3484 void
3485 Function::check_labels() const
3487 for (Labels::const_iterator p = this->labels_.begin();
3488 p != this->labels_.end();
3489 p++)
3491 Label* label = p->second;
3492 if (!label->is_used())
3493 error_at(label->location(), "label %qs defined and not used",
3494 Gogo::message_name(label->name()).c_str());
3498 // Swap one function with another. This is used when building the
3499 // thunk we use to call a function which calls recover. It may not
3500 // work for any other case.
3502 void
3503 Function::swap_for_recover(Function *x)
3505 go_assert(this->enclosing_ == x->enclosing_);
3506 std::swap(this->results_, x->results_);
3507 std::swap(this->closure_var_, x->closure_var_);
3508 std::swap(this->block_, x->block_);
3509 go_assert(this->location_ == x->location_);
3510 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3511 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3514 // Traverse the tree.
3517 Function::traverse(Traverse* traverse)
3519 unsigned int traverse_mask = traverse->traverse_mask();
3521 if ((traverse_mask
3522 & (Traverse::traverse_types | Traverse::traverse_expressions))
3523 != 0)
3525 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3526 return TRAVERSE_EXIT;
3529 // FIXME: We should check traverse_functions here if nested
3530 // functions are stored in block bindings.
3531 if (this->block_ != NULL
3532 && (traverse_mask
3533 & (Traverse::traverse_variables
3534 | Traverse::traverse_constants
3535 | Traverse::traverse_blocks
3536 | Traverse::traverse_statements
3537 | Traverse::traverse_expressions
3538 | Traverse::traverse_types)) != 0)
3540 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3541 return TRAVERSE_EXIT;
3544 return TRAVERSE_CONTINUE;
3547 // Work out types for unspecified variables and constants.
3549 void
3550 Function::determine_types()
3552 if (this->block_ != NULL)
3553 this->block_->determine_types();
3556 // Build a wrapper function for a function descriptor. A function
3557 // descriptor refers to a function that takes a closure as its last
3558 // argument. In this case there will be no closure, but an indirect
3559 // call will pass nil as the last argument. We need to build a
3560 // wrapper function that accepts and discards that last argument, so
3561 // that cases like -mrtd will work correctly. In most cases the
3562 // wrapper function will simply be a jump.
3564 Named_object*
3565 Function::make_descriptor_wrapper(Gogo* gogo, Named_object* no,
3566 Function_type* orig_fntype)
3568 Location loc = no->location();
3570 Type* vt = Type::make_pointer_type(Type::make_void_type());
3571 Function_type* new_fntype = orig_fntype->copy_with_closure(vt);
3573 std::string name = no->name() + "$descriptorfn";
3574 Named_object* dno = gogo->start_function(name, new_fntype, false, loc);
3575 dno->func_value()->is_descriptor_wrapper_ = true;
3577 gogo->start_block(loc);
3579 Expression* fn = Expression::make_func_reference(no, NULL, loc);
3581 // Call the function begin wrapped, passing all of the arguments
3582 // except for the last one (the last argument is the ignored
3583 // closure).
3584 const Typed_identifier_list* orig_params = orig_fntype->parameters();
3585 Expression_list* args;
3586 if (orig_params == NULL || orig_params->empty())
3587 args = NULL;
3588 else
3590 const Typed_identifier_list* new_params = new_fntype->parameters();
3591 args = new Expression_list();
3592 for (Typed_identifier_list::const_iterator p = new_params->begin();
3593 p + 1 != new_params->end();
3594 ++p)
3596 Named_object* p_no = gogo->lookup(p->name(), NULL);
3597 go_assert(p_no != NULL
3598 && p_no->is_variable()
3599 && p_no->var_value()->is_parameter());
3600 args->push_back(Expression::make_var_reference(p_no, loc));
3604 Call_expression* call = Expression::make_call(fn, args,
3605 orig_fntype->is_varargs(),
3606 loc);
3607 call->set_varargs_are_lowered();
3609 Statement* s = Statement::make_return_from_call(call, loc);
3610 gogo->add_statement(s);
3611 Block* b = gogo->finish_block(loc);
3612 gogo->add_block(b, loc);
3613 gogo->lower_block(dno, b);
3614 gogo->finish_function(loc);
3616 return dno;
3619 // Return the function descriptor, the value you get when you refer to
3620 // the function in Go code without calling it.
3622 Expression*
3623 Function::descriptor(Gogo* gogo, Named_object* no)
3625 go_assert(!this->is_method());
3626 go_assert(this->closure_var_ == NULL);
3627 go_assert(!this->is_descriptor_wrapper_);
3628 if (this->descriptor_ == NULL)
3630 // Make and record the descriptor first, so that when we lower
3631 // the descriptor wrapper we don't try to make it again.
3632 Func_descriptor_expression* descriptor =
3633 Expression::make_func_descriptor(no);
3634 this->descriptor_ = descriptor;
3635 if (no->package() == NULL
3636 && !Linemap::is_predeclared_location(no->location()))
3638 Named_object* dno = Function::make_descriptor_wrapper(gogo, no,
3639 this->type_);
3640 descriptor->set_descriptor_wrapper(dno);
3643 return this->descriptor_;
3646 // Get a pointer to the variable representing the defer stack for this
3647 // function, making it if necessary. The value of the variable is set
3648 // by the runtime routines to true if the function is returning,
3649 // rather than panicing through. A pointer to this variable is used
3650 // as a marker for the functions on the defer stack associated with
3651 // this function. A function-specific variable permits inlining a
3652 // function which uses defer.
3654 Expression*
3655 Function::defer_stack(Location location)
3657 if (this->defer_stack_ == NULL)
3659 Type* t = Type::lookup_bool_type();
3660 Expression* n = Expression::make_boolean(false, location);
3661 this->defer_stack_ = Statement::make_temporary(t, n, location);
3662 this->defer_stack_->set_is_address_taken();
3664 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3665 location);
3666 return Expression::make_unary(OPERATOR_AND, ref, location);
3669 // Export the function.
3671 void
3672 Function::export_func(Export* exp, const std::string& name) const
3674 Function::export_func_with_type(exp, name, this->type_);
3677 // Export a function with a type.
3679 void
3680 Function::export_func_with_type(Export* exp, const std::string& name,
3681 const Function_type* fntype)
3683 exp->write_c_string("func ");
3685 if (fntype->is_method())
3687 exp->write_c_string("(");
3688 const Typed_identifier* receiver = fntype->receiver();
3689 exp->write_name(receiver->name());
3690 exp->write_c_string(" ");
3691 exp->write_type(receiver->type());
3692 exp->write_c_string(") ");
3695 exp->write_string(name);
3697 exp->write_c_string(" (");
3698 const Typed_identifier_list* parameters = fntype->parameters();
3699 if (parameters != NULL)
3701 bool is_varargs = fntype->is_varargs();
3702 bool first = true;
3703 for (Typed_identifier_list::const_iterator p = parameters->begin();
3704 p != parameters->end();
3705 ++p)
3707 if (first)
3708 first = false;
3709 else
3710 exp->write_c_string(", ");
3711 exp->write_name(p->name());
3712 exp->write_c_string(" ");
3713 if (!is_varargs || p + 1 != parameters->end())
3714 exp->write_type(p->type());
3715 else
3717 exp->write_c_string("...");
3718 exp->write_type(p->type()->array_type()->element_type());
3722 exp->write_c_string(")");
3724 const Typed_identifier_list* results = fntype->results();
3725 if (results != NULL)
3727 if (results->size() == 1 && results->begin()->name().empty())
3729 exp->write_c_string(" ");
3730 exp->write_type(results->begin()->type());
3732 else
3734 exp->write_c_string(" (");
3735 bool first = true;
3736 for (Typed_identifier_list::const_iterator p = results->begin();
3737 p != results->end();
3738 ++p)
3740 if (first)
3741 first = false;
3742 else
3743 exp->write_c_string(", ");
3744 exp->write_name(p->name());
3745 exp->write_c_string(" ");
3746 exp->write_type(p->type());
3748 exp->write_c_string(")");
3751 exp->write_c_string(";\n");
3754 // Import a function.
3756 void
3757 Function::import_func(Import* imp, std::string* pname,
3758 Typed_identifier** preceiver,
3759 Typed_identifier_list** pparameters,
3760 Typed_identifier_list** presults,
3761 bool* is_varargs)
3763 imp->require_c_string("func ");
3765 *preceiver = NULL;
3766 if (imp->peek_char() == '(')
3768 imp->require_c_string("(");
3769 std::string name = imp->read_name();
3770 imp->require_c_string(" ");
3771 Type* rtype = imp->read_type();
3772 *preceiver = new Typed_identifier(name, rtype, imp->location());
3773 imp->require_c_string(") ");
3776 *pname = imp->read_identifier();
3778 Typed_identifier_list* parameters;
3779 *is_varargs = false;
3780 imp->require_c_string(" (");
3781 if (imp->peek_char() == ')')
3782 parameters = NULL;
3783 else
3785 parameters = new Typed_identifier_list();
3786 while (true)
3788 std::string name = imp->read_name();
3789 imp->require_c_string(" ");
3791 if (imp->match_c_string("..."))
3793 imp->advance(3);
3794 *is_varargs = true;
3797 Type* ptype = imp->read_type();
3798 if (*is_varargs)
3799 ptype = Type::make_array_type(ptype, NULL);
3800 parameters->push_back(Typed_identifier(name, ptype,
3801 imp->location()));
3802 if (imp->peek_char() != ',')
3803 break;
3804 go_assert(!*is_varargs);
3805 imp->require_c_string(", ");
3808 imp->require_c_string(")");
3809 *pparameters = parameters;
3811 Typed_identifier_list* results;
3812 if (imp->peek_char() != ' ')
3813 results = NULL;
3814 else
3816 results = new Typed_identifier_list();
3817 imp->require_c_string(" ");
3818 if (imp->peek_char() != '(')
3820 Type* rtype = imp->read_type();
3821 results->push_back(Typed_identifier("", rtype, imp->location()));
3823 else
3825 imp->require_c_string("(");
3826 while (true)
3828 std::string name = imp->read_name();
3829 imp->require_c_string(" ");
3830 Type* rtype = imp->read_type();
3831 results->push_back(Typed_identifier(name, rtype,
3832 imp->location()));
3833 if (imp->peek_char() != ',')
3834 break;
3835 imp->require_c_string(", ");
3837 imp->require_c_string(")");
3840 imp->require_c_string(";\n");
3841 *presults = results;
3844 // Class Block.
3846 Block::Block(Block* enclosing, Location location)
3847 : enclosing_(enclosing), statements_(),
3848 bindings_(new Bindings(enclosing == NULL
3849 ? NULL
3850 : enclosing->bindings())),
3851 start_location_(location),
3852 end_location_(UNKNOWN_LOCATION)
3856 // Add a statement to a block.
3858 void
3859 Block::add_statement(Statement* statement)
3861 this->statements_.push_back(statement);
3864 // Add a statement to the front of a block. This is slow but is only
3865 // used for reference counts of parameters.
3867 void
3868 Block::add_statement_at_front(Statement* statement)
3870 this->statements_.insert(this->statements_.begin(), statement);
3873 // Replace a statement in a block.
3875 void
3876 Block::replace_statement(size_t index, Statement* s)
3878 go_assert(index < this->statements_.size());
3879 this->statements_[index] = s;
3882 // Add a statement before another statement.
3884 void
3885 Block::insert_statement_before(size_t index, Statement* s)
3887 go_assert(index < this->statements_.size());
3888 this->statements_.insert(this->statements_.begin() + index, s);
3891 // Add a statement after another statement.
3893 void
3894 Block::insert_statement_after(size_t index, Statement* s)
3896 go_assert(index < this->statements_.size());
3897 this->statements_.insert(this->statements_.begin() + index + 1, s);
3900 // Traverse the tree.
3903 Block::traverse(Traverse* traverse)
3905 unsigned int traverse_mask = traverse->traverse_mask();
3907 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3909 int t = traverse->block(this);
3910 if (t == TRAVERSE_EXIT)
3911 return TRAVERSE_EXIT;
3912 else if (t == TRAVERSE_SKIP_COMPONENTS)
3913 return TRAVERSE_CONTINUE;
3916 if ((traverse_mask
3917 & (Traverse::traverse_variables
3918 | Traverse::traverse_constants
3919 | Traverse::traverse_expressions
3920 | Traverse::traverse_types)) != 0)
3922 const unsigned int e_or_t = (Traverse::traverse_expressions
3923 | Traverse::traverse_types);
3924 const unsigned int e_or_t_or_s = (e_or_t
3925 | Traverse::traverse_statements);
3926 for (Bindings::const_definitions_iterator pb =
3927 this->bindings_->begin_definitions();
3928 pb != this->bindings_->end_definitions();
3929 ++pb)
3931 int t = TRAVERSE_CONTINUE;
3932 switch ((*pb)->classification())
3934 case Named_object::NAMED_OBJECT_CONST:
3935 if ((traverse_mask & Traverse::traverse_constants) != 0)
3936 t = traverse->constant(*pb, false);
3937 if (t == TRAVERSE_CONTINUE
3938 && (traverse_mask & e_or_t) != 0)
3940 Type* tc = (*pb)->const_value()->type();
3941 if (tc != NULL
3942 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3943 return TRAVERSE_EXIT;
3944 t = (*pb)->const_value()->traverse_expression(traverse);
3946 break;
3948 case Named_object::NAMED_OBJECT_VAR:
3949 case Named_object::NAMED_OBJECT_RESULT_VAR:
3950 if ((traverse_mask & Traverse::traverse_variables) != 0)
3951 t = traverse->variable(*pb);
3952 if (t == TRAVERSE_CONTINUE
3953 && (traverse_mask & e_or_t) != 0)
3955 if ((*pb)->is_result_variable()
3956 || (*pb)->var_value()->has_type())
3958 Type* tv = ((*pb)->is_variable()
3959 ? (*pb)->var_value()->type()
3960 : (*pb)->result_var_value()->type());
3961 if (tv != NULL
3962 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3963 return TRAVERSE_EXIT;
3966 if (t == TRAVERSE_CONTINUE
3967 && (traverse_mask & e_or_t_or_s) != 0
3968 && (*pb)->is_variable())
3969 t = (*pb)->var_value()->traverse_expression(traverse,
3970 traverse_mask);
3971 break;
3973 case Named_object::NAMED_OBJECT_FUNC:
3974 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3975 go_unreachable();
3977 case Named_object::NAMED_OBJECT_TYPE:
3978 if ((traverse_mask & e_or_t) != 0)
3979 t = Type::traverse((*pb)->type_value(), traverse);
3980 break;
3982 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3983 case Named_object::NAMED_OBJECT_UNKNOWN:
3984 case Named_object::NAMED_OBJECT_ERRONEOUS:
3985 break;
3987 case Named_object::NAMED_OBJECT_PACKAGE:
3988 case Named_object::NAMED_OBJECT_SINK:
3989 go_unreachable();
3991 default:
3992 go_unreachable();
3995 if (t == TRAVERSE_EXIT)
3996 return TRAVERSE_EXIT;
4000 // No point in checking traverse_mask here--if we got here we always
4001 // want to walk the statements. The traversal can insert new
4002 // statements before or after the current statement. Inserting
4003 // statements before the current statement requires updating I via
4004 // the pointer; those statements will not be traversed. Any new
4005 // statements inserted after the current statement will be traversed
4006 // in their turn.
4007 for (size_t i = 0; i < this->statements_.size(); ++i)
4009 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
4010 return TRAVERSE_EXIT;
4013 return TRAVERSE_CONTINUE;
4016 // Work out types for unspecified variables and constants.
4018 void
4019 Block::determine_types()
4021 for (Bindings::const_definitions_iterator pb =
4022 this->bindings_->begin_definitions();
4023 pb != this->bindings_->end_definitions();
4024 ++pb)
4026 if ((*pb)->is_variable())
4027 (*pb)->var_value()->determine_type();
4028 else if ((*pb)->is_const())
4029 (*pb)->const_value()->determine_type();
4032 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
4033 ps != this->statements_.end();
4034 ++ps)
4035 (*ps)->determine_types();
4038 // Return true if the statements in this block may fall through.
4040 bool
4041 Block::may_fall_through() const
4043 if (this->statements_.empty())
4044 return true;
4045 return this->statements_.back()->may_fall_through();
4048 // Convert a block to the backend representation.
4050 Bblock*
4051 Block::get_backend(Translate_context* context)
4053 Gogo* gogo = context->gogo();
4054 Named_object* function = context->function();
4055 std::vector<Bvariable*> vars;
4056 vars.reserve(this->bindings_->size_definitions());
4057 for (Bindings::const_definitions_iterator pv =
4058 this->bindings_->begin_definitions();
4059 pv != this->bindings_->end_definitions();
4060 ++pv)
4062 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
4063 vars.push_back((*pv)->get_backend_variable(gogo, function));
4066 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
4067 // until we have a proper representation of the init function.
4068 Bfunction* bfunction;
4069 if (function == NULL)
4070 bfunction = NULL;
4071 else
4072 bfunction = tree_to_function(function->func_value()->get_decl());
4073 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
4074 vars, this->start_location_,
4075 this->end_location_);
4077 Translate_context subcontext(gogo, function, this, ret);
4078 std::vector<Bstatement*> bstatements;
4079 bstatements.reserve(this->statements_.size());
4080 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
4081 p != this->statements_.end();
4082 ++p)
4083 bstatements.push_back((*p)->get_backend(&subcontext));
4085 context->backend()->block_add_statements(ret, bstatements);
4087 return ret;
4090 // Class Bindings_snapshot.
4092 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
4093 : block_(b), counts_(), location_(location)
4095 while (b != NULL)
4097 this->counts_.push_back(b->bindings()->size_definitions());
4098 b = b->enclosing();
4102 // Report errors appropriate for a goto from B to this.
4104 void
4105 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
4107 size_t dummy;
4108 if (!this->check_goto_block(loc, b, this->block_, &dummy))
4109 return;
4110 this->check_goto_defs(loc, this->block_,
4111 this->block_->bindings()->size_definitions(),
4112 this->counts_[0]);
4115 // Report errors appropriate for a goto from this to B.
4117 void
4118 Bindings_snapshot::check_goto_to(const Block* b)
4120 size_t index;
4121 if (!this->check_goto_block(this->location_, this->block_, b, &index))
4122 return;
4123 this->check_goto_defs(this->location_, b, this->counts_[index],
4124 b->bindings()->size_definitions());
4127 // Report errors appropriate for a goto at LOC from BFROM to BTO.
4128 // Return true if all is well, false if we reported an error. If this
4129 // returns true, it sets *PINDEX to the number of blocks BTO is above
4130 // BFROM.
4132 bool
4133 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
4134 const Block* bto, size_t* pindex)
4136 // It is an error if BTO is not either BFROM or above BFROM.
4137 size_t index = 0;
4138 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
4140 if (pb == NULL)
4142 error_at(loc, "goto jumps into block");
4143 inform(bto->start_location(), "goto target block starts here");
4144 return false;
4147 *pindex = index;
4148 return true;
4151 // Report errors appropriate for a goto at LOC ending at BLOCK, where
4152 // CFROM is the number of names defined at the point of the goto and
4153 // CTO is the number of names defined at the point of the label.
4155 void
4156 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
4157 size_t cfrom, size_t cto)
4159 if (cfrom < cto)
4161 Bindings::const_definitions_iterator p =
4162 block->bindings()->begin_definitions();
4163 for (size_t i = 0; i < cfrom; ++i)
4165 go_assert(p != block->bindings()->end_definitions());
4166 ++p;
4168 go_assert(p != block->bindings()->end_definitions());
4170 std::string n = (*p)->message_name();
4171 error_at(loc, "goto jumps over declaration of %qs", n.c_str());
4172 inform((*p)->location(), "%qs defined here", n.c_str());
4176 // Class Function_declaration.
4178 // Return the function descriptor.
4180 Expression*
4181 Function_declaration::descriptor(Gogo* gogo, Named_object* no)
4183 go_assert(!this->fntype_->is_method());
4184 if (this->descriptor_ == NULL)
4186 // Make and record the descriptor first, so that when we lower
4187 // the descriptor wrapper we don't try to make it again.
4188 Func_descriptor_expression* descriptor =
4189 Expression::make_func_descriptor(no);
4190 this->descriptor_ = descriptor;
4191 if (no->package() == NULL
4192 && !Linemap::is_predeclared_location(no->location()))
4194 Named_object* dno = Function::make_descriptor_wrapper(gogo, no,
4195 this->fntype_);
4196 descriptor->set_descriptor_wrapper(dno);
4199 return this->descriptor_;
4202 // Class Variable.
4204 Variable::Variable(Type* type, Expression* init, bool is_global,
4205 bool is_parameter, bool is_receiver,
4206 Location location)
4207 : type_(type), init_(init), preinit_(NULL), location_(location),
4208 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
4209 is_receiver_(is_receiver), is_varargs_parameter_(false), is_used_(false),
4210 is_address_taken_(false), is_non_escaping_address_taken_(false),
4211 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
4212 type_from_range_index_(false), type_from_range_value_(false),
4213 type_from_chan_element_(false), is_type_switch_var_(false),
4214 determined_type_(false), in_unique_section_(false)
4216 go_assert(type != NULL || init != NULL);
4217 go_assert(!is_parameter || init == NULL);
4220 // Traverse the initializer expression.
4223 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
4225 if (this->preinit_ != NULL)
4227 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
4228 return TRAVERSE_EXIT;
4230 if (this->init_ != NULL
4231 && ((traverse_mask
4232 & (Traverse::traverse_expressions | Traverse::traverse_types))
4233 != 0))
4235 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
4236 return TRAVERSE_EXIT;
4238 return TRAVERSE_CONTINUE;
4241 // Lower the initialization expression after parsing is complete.
4243 void
4244 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
4245 Statement_inserter* inserter)
4247 Named_object* dep = gogo->var_depends_on(this);
4248 if (dep != NULL && dep->is_variable())
4249 dep->var_value()->lower_init_expression(gogo, function, inserter);
4251 if (this->init_ != NULL && !this->init_is_lowered_)
4253 if (this->seen_)
4255 // We will give an error elsewhere, this is just to prevent
4256 // an infinite loop.
4257 return;
4259 this->seen_ = true;
4261 Statement_inserter global_inserter;
4262 if (this->is_global_)
4264 global_inserter = Statement_inserter(gogo, this);
4265 inserter = &global_inserter;
4268 gogo->lower_expression(function, inserter, &this->init_);
4270 this->seen_ = false;
4272 this->init_is_lowered_ = true;
4276 // Get the preinit block.
4278 Block*
4279 Variable::preinit_block(Gogo* gogo)
4281 go_assert(this->is_global_);
4282 if (this->preinit_ == NULL)
4283 this->preinit_ = new Block(NULL, this->location());
4285 // If a global variable has a preinitialization statement, then we
4286 // need to have an initialization function.
4287 gogo->set_need_init_fn();
4289 return this->preinit_;
4292 // Add a statement to be run before the initialization expression.
4294 void
4295 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
4297 Block* b = this->preinit_block(gogo);
4298 b->add_statement(s);
4299 b->set_end_location(s->location());
4302 // Whether this variable has a type.
4304 bool
4305 Variable::has_type() const
4307 if (this->type_ == NULL)
4308 return false;
4310 // A variable created in a type switch case nil does not actually
4311 // have a type yet. It will be changed to use the initializer's
4312 // type in determine_type.
4313 if (this->is_type_switch_var_
4314 && this->type_->is_nil_constant_as_type())
4315 return false;
4317 return true;
4320 // In an assignment which sets a variable to a tuple of EXPR, return
4321 // the type of the first element of the tuple.
4323 Type*
4324 Variable::type_from_tuple(Expression* expr, bool report_error) const
4326 if (expr->map_index_expression() != NULL)
4328 Map_type* mt = expr->map_index_expression()->get_map_type();
4329 if (mt == NULL)
4330 return Type::make_error_type();
4331 return mt->val_type();
4333 else if (expr->receive_expression() != NULL)
4335 Expression* channel = expr->receive_expression()->channel();
4336 Type* channel_type = channel->type();
4337 if (channel_type->channel_type() == NULL)
4338 return Type::make_error_type();
4339 return channel_type->channel_type()->element_type();
4341 else
4343 if (report_error)
4344 error_at(this->location(), "invalid tuple definition");
4345 return Type::make_error_type();
4349 // Given EXPR used in a range clause, return either the index type or
4350 // the value type of the range, depending upon GET_INDEX_TYPE.
4352 Type*
4353 Variable::type_from_range(Expression* expr, bool get_index_type,
4354 bool report_error) const
4356 Type* t = expr->type();
4357 if (t->array_type() != NULL
4358 || (t->points_to() != NULL
4359 && t->points_to()->array_type() != NULL
4360 && !t->points_to()->is_slice_type()))
4362 if (get_index_type)
4363 return Type::lookup_integer_type("int");
4364 else
4365 return t->deref()->array_type()->element_type();
4367 else if (t->is_string_type())
4369 if (get_index_type)
4370 return Type::lookup_integer_type("int");
4371 else
4372 return Type::lookup_integer_type("int32");
4374 else if (t->map_type() != NULL)
4376 if (get_index_type)
4377 return t->map_type()->key_type();
4378 else
4379 return t->map_type()->val_type();
4381 else if (t->channel_type() != NULL)
4383 if (get_index_type)
4384 return t->channel_type()->element_type();
4385 else
4387 if (report_error)
4388 error_at(this->location(),
4389 "invalid definition of value variable for channel range");
4390 return Type::make_error_type();
4393 else
4395 if (report_error)
4396 error_at(this->location(), "invalid type for range clause");
4397 return Type::make_error_type();
4401 // EXPR should be a channel. Return the channel's element type.
4403 Type*
4404 Variable::type_from_chan_element(Expression* expr, bool report_error) const
4406 Type* t = expr->type();
4407 if (t->channel_type() != NULL)
4408 return t->channel_type()->element_type();
4409 else
4411 if (report_error)
4412 error_at(this->location(), "expected channel");
4413 return Type::make_error_type();
4417 // Return the type of the Variable. This may be called before
4418 // Variable::determine_type is called, which means that we may need to
4419 // get the type from the initializer. FIXME: If we combine lowering
4420 // with type determination, then this should be unnecessary.
4422 Type*
4423 Variable::type()
4425 // A variable in a type switch with a nil case will have the wrong
4426 // type here. This gets fixed up in determine_type, below.
4427 Type* type = this->type_;
4428 Expression* init = this->init_;
4429 if (this->is_type_switch_var_
4430 && this->type_->is_nil_constant_as_type())
4432 Type_guard_expression* tge = this->init_->type_guard_expression();
4433 go_assert(tge != NULL);
4434 init = tge->expr();
4435 type = NULL;
4438 if (this->seen_)
4440 if (this->type_ == NULL || !this->type_->is_error_type())
4442 error_at(this->location_, "variable initializer refers to itself");
4443 this->type_ = Type::make_error_type();
4445 return this->type_;
4448 this->seen_ = true;
4450 if (type != NULL)
4452 else if (this->type_from_init_tuple_)
4453 type = this->type_from_tuple(init, false);
4454 else if (this->type_from_range_index_ || this->type_from_range_value_)
4455 type = this->type_from_range(init, this->type_from_range_index_, false);
4456 else if (this->type_from_chan_element_)
4457 type = this->type_from_chan_element(init, false);
4458 else
4460 go_assert(init != NULL);
4461 type = init->type();
4462 go_assert(type != NULL);
4464 // Variables should not have abstract types.
4465 if (type->is_abstract())
4466 type = type->make_non_abstract_type();
4468 if (type->is_void_type())
4469 type = Type::make_error_type();
4472 this->seen_ = false;
4474 return type;
4477 // Fetch the type from a const pointer, in which case it should have
4478 // been set already.
4480 Type*
4481 Variable::type() const
4483 go_assert(this->type_ != NULL);
4484 return this->type_;
4487 // Set the type if necessary.
4489 void
4490 Variable::determine_type()
4492 if (this->determined_type_)
4493 return;
4494 this->determined_type_ = true;
4496 if (this->preinit_ != NULL)
4497 this->preinit_->determine_types();
4499 // A variable in a type switch with a nil case will have the wrong
4500 // type here. It will have an initializer which is a type guard.
4501 // We want to initialize it to the value without the type guard, and
4502 // use the type of that value as well.
4503 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
4505 Type_guard_expression* tge = this->init_->type_guard_expression();
4506 go_assert(tge != NULL);
4507 this->type_ = NULL;
4508 this->init_ = tge->expr();
4511 if (this->init_ == NULL)
4512 go_assert(this->type_ != NULL && !this->type_->is_abstract());
4513 else if (this->type_from_init_tuple_)
4515 Expression *init = this->init_;
4516 init->determine_type_no_context();
4517 this->type_ = this->type_from_tuple(init, true);
4518 this->init_ = NULL;
4520 else if (this->type_from_range_index_ || this->type_from_range_value_)
4522 Expression* init = this->init_;
4523 init->determine_type_no_context();
4524 this->type_ = this->type_from_range(init, this->type_from_range_index_,
4525 true);
4526 this->init_ = NULL;
4528 else if (this->type_from_chan_element_)
4530 Expression* init = this->init_;
4531 init->determine_type_no_context();
4532 this->type_ = this->type_from_chan_element(init, true);
4533 this->init_ = NULL;
4535 else
4537 Type_context context(this->type_, false);
4538 this->init_->determine_type(&context);
4539 if (this->type_ == NULL)
4541 Type* type = this->init_->type();
4542 go_assert(type != NULL);
4543 if (type->is_abstract())
4544 type = type->make_non_abstract_type();
4546 if (type->is_void_type())
4548 error_at(this->location_, "variable has no type");
4549 type = Type::make_error_type();
4551 else if (type->is_nil_type())
4553 error_at(this->location_, "variable defined to nil type");
4554 type = Type::make_error_type();
4556 else if (type->is_call_multiple_result_type())
4558 error_at(this->location_,
4559 "single variable set to multiple-value function call");
4560 type = Type::make_error_type();
4563 this->type_ = type;
4568 // Export the variable
4570 void
4571 Variable::export_var(Export* exp, const std::string& name) const
4573 go_assert(this->is_global_);
4574 exp->write_c_string("var ");
4575 exp->write_string(name);
4576 exp->write_c_string(" ");
4577 exp->write_type(this->type());
4578 exp->write_c_string(";\n");
4581 // Import a variable.
4583 void
4584 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
4586 imp->require_c_string("var ");
4587 *pname = imp->read_identifier();
4588 imp->require_c_string(" ");
4589 *ptype = imp->read_type();
4590 imp->require_c_string(";\n");
4593 // Convert a variable to the backend representation.
4595 Bvariable*
4596 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
4597 const Package* package, const std::string& name)
4599 if (this->backend_ == NULL)
4601 Backend* backend = gogo->backend();
4602 Type* type = this->type_;
4603 if (type->is_error_type()
4604 || (type->is_undefined()
4605 && (!this->is_global_ || package == NULL)))
4606 this->backend_ = backend->error_variable();
4607 else
4609 bool is_parameter = this->is_parameter_;
4610 if (this->is_receiver_ && type->points_to() == NULL)
4611 is_parameter = false;
4612 if (this->is_in_heap())
4614 is_parameter = false;
4615 type = Type::make_pointer_type(type);
4618 std::string n = Gogo::unpack_hidden_name(name);
4619 Btype* btype = type->get_backend(gogo);
4621 Bvariable* bvar;
4622 if (this->is_global_)
4623 bvar = backend->global_variable((package == NULL
4624 ? gogo->package_name()
4625 : package->package_name()),
4626 (package == NULL
4627 ? gogo->pkgpath_symbol()
4628 : package->pkgpath_symbol()),
4630 btype,
4631 package != NULL,
4632 Gogo::is_hidden_name(name),
4633 this->in_unique_section_,
4634 this->location_);
4635 else if (function == NULL)
4637 go_assert(saw_errors());
4638 bvar = backend->error_variable();
4640 else
4642 tree fndecl = function->func_value()->get_decl();
4643 Bfunction* bfunction = tree_to_function(fndecl);
4644 bool is_address_taken = (this->is_non_escaping_address_taken_
4645 && !this->is_in_heap());
4646 if (is_parameter)
4647 bvar = backend->parameter_variable(bfunction, n, btype,
4648 is_address_taken,
4649 this->location_);
4650 else
4651 bvar = backend->local_variable(bfunction, n, btype,
4652 is_address_taken,
4653 this->location_);
4655 this->backend_ = bvar;
4658 return this->backend_;
4661 // Class Result_variable.
4663 // Convert a result variable to the backend representation.
4665 Bvariable*
4666 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
4667 const std::string& name)
4669 if (this->backend_ == NULL)
4671 Backend* backend = gogo->backend();
4672 Type* type = this->type_;
4673 if (type->is_error())
4674 this->backend_ = backend->error_variable();
4675 else
4677 if (this->is_in_heap())
4678 type = Type::make_pointer_type(type);
4679 Btype* btype = type->get_backend(gogo);
4680 tree fndecl = function->func_value()->get_decl();
4681 Bfunction* bfunction = tree_to_function(fndecl);
4682 std::string n = Gogo::unpack_hidden_name(name);
4683 bool is_address_taken = (this->is_non_escaping_address_taken_
4684 && !this->is_in_heap());
4685 this->backend_ = backend->local_variable(bfunction, n, btype,
4686 is_address_taken,
4687 this->location_);
4690 return this->backend_;
4693 // Class Named_constant.
4695 // Traverse the initializer expression.
4698 Named_constant::traverse_expression(Traverse* traverse)
4700 return Expression::traverse(&this->expr_, traverse);
4703 // Determine the type of the constant.
4705 void
4706 Named_constant::determine_type()
4708 if (this->type_ != NULL)
4710 Type_context context(this->type_, false);
4711 this->expr_->determine_type(&context);
4713 else
4715 // A constant may have an abstract type.
4716 Type_context context(NULL, true);
4717 this->expr_->determine_type(&context);
4718 this->type_ = this->expr_->type();
4719 go_assert(this->type_ != NULL);
4723 // Indicate that we found and reported an error for this constant.
4725 void
4726 Named_constant::set_error()
4728 this->type_ = Type::make_error_type();
4729 this->expr_ = Expression::make_error(this->location_);
4732 // Export a constant.
4734 void
4735 Named_constant::export_const(Export* exp, const std::string& name) const
4737 exp->write_c_string("const ");
4738 exp->write_string(name);
4739 exp->write_c_string(" ");
4740 if (!this->type_->is_abstract())
4742 exp->write_type(this->type_);
4743 exp->write_c_string(" ");
4745 exp->write_c_string("= ");
4746 this->expr()->export_expression(exp);
4747 exp->write_c_string(";\n");
4750 // Import a constant.
4752 void
4753 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
4754 Expression** pexpr)
4756 imp->require_c_string("const ");
4757 *pname = imp->read_identifier();
4758 imp->require_c_string(" ");
4759 if (imp->peek_char() == '=')
4760 *ptype = NULL;
4761 else
4763 *ptype = imp->read_type();
4764 imp->require_c_string(" ");
4766 imp->require_c_string("= ");
4767 *pexpr = Expression::import_expression(imp);
4768 imp->require_c_string(";\n");
4771 // Add a method.
4773 Named_object*
4774 Type_declaration::add_method(const std::string& name, Function* function)
4776 Named_object* ret = Named_object::make_function(name, NULL, function);
4777 this->methods_.push_back(ret);
4778 return ret;
4781 // Add a method declaration.
4783 Named_object*
4784 Type_declaration::add_method_declaration(const std::string& name,
4785 Package* package,
4786 Function_type* type,
4787 Location location)
4789 Named_object* ret = Named_object::make_function_declaration(name, package,
4790 type, location);
4791 this->methods_.push_back(ret);
4792 return ret;
4795 // Return whether any methods ere defined.
4797 bool
4798 Type_declaration::has_methods() const
4800 return !this->methods_.empty();
4803 // Define methods for the real type.
4805 void
4806 Type_declaration::define_methods(Named_type* nt)
4808 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
4809 p != this->methods_.end();
4810 ++p)
4811 nt->add_existing_method(*p);
4814 // We are using the type. Return true if we should issue a warning.
4816 bool
4817 Type_declaration::using_type()
4819 bool ret = !this->issued_warning_;
4820 this->issued_warning_ = true;
4821 return ret;
4824 // Class Unknown_name.
4826 // Set the real named object.
4828 void
4829 Unknown_name::set_real_named_object(Named_object* no)
4831 go_assert(this->real_named_object_ == NULL);
4832 go_assert(!no->is_unknown());
4833 this->real_named_object_ = no;
4836 // Class Named_object.
4838 Named_object::Named_object(const std::string& name,
4839 const Package* package,
4840 Classification classification)
4841 : name_(name), package_(package), classification_(classification),
4842 tree_(NULL)
4844 if (Gogo::is_sink_name(name))
4845 go_assert(classification == NAMED_OBJECT_SINK);
4848 // Make an unknown name. This is used by the parser. The name must
4849 // be resolved later. Unknown names are only added in the current
4850 // package.
4852 Named_object*
4853 Named_object::make_unknown_name(const std::string& name,
4854 Location location)
4856 Named_object* named_object = new Named_object(name, NULL,
4857 NAMED_OBJECT_UNKNOWN);
4858 Unknown_name* value = new Unknown_name(location);
4859 named_object->u_.unknown_value = value;
4860 return named_object;
4863 // Make a constant.
4865 Named_object*
4866 Named_object::make_constant(const Typed_identifier& tid,
4867 const Package* package, Expression* expr,
4868 int iota_value)
4870 Named_object* named_object = new Named_object(tid.name(), package,
4871 NAMED_OBJECT_CONST);
4872 Named_constant* named_constant = new Named_constant(tid.type(), expr,
4873 iota_value,
4874 tid.location());
4875 named_object->u_.const_value = named_constant;
4876 return named_object;
4879 // Make a named type.
4881 Named_object*
4882 Named_object::make_type(const std::string& name, const Package* package,
4883 Type* type, Location location)
4885 Named_object* named_object = new Named_object(name, package,
4886 NAMED_OBJECT_TYPE);
4887 Named_type* named_type = Type::make_named_type(named_object, type, location);
4888 named_object->u_.type_value = named_type;
4889 return named_object;
4892 // Make a type declaration.
4894 Named_object*
4895 Named_object::make_type_declaration(const std::string& name,
4896 const Package* package,
4897 Location location)
4899 Named_object* named_object = new Named_object(name, package,
4900 NAMED_OBJECT_TYPE_DECLARATION);
4901 Type_declaration* type_declaration = new Type_declaration(location);
4902 named_object->u_.type_declaration = type_declaration;
4903 return named_object;
4906 // Make a variable.
4908 Named_object*
4909 Named_object::make_variable(const std::string& name, const Package* package,
4910 Variable* variable)
4912 Named_object* named_object = new Named_object(name, package,
4913 NAMED_OBJECT_VAR);
4914 named_object->u_.var_value = variable;
4915 return named_object;
4918 // Make a result variable.
4920 Named_object*
4921 Named_object::make_result_variable(const std::string& name,
4922 Result_variable* result)
4924 Named_object* named_object = new Named_object(name, NULL,
4925 NAMED_OBJECT_RESULT_VAR);
4926 named_object->u_.result_var_value = result;
4927 return named_object;
4930 // Make a sink. This is used for the special blank identifier _.
4932 Named_object*
4933 Named_object::make_sink()
4935 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4938 // Make a named function.
4940 Named_object*
4941 Named_object::make_function(const std::string& name, const Package* package,
4942 Function* function)
4944 Named_object* named_object = new Named_object(name, package,
4945 NAMED_OBJECT_FUNC);
4946 named_object->u_.func_value = function;
4947 return named_object;
4950 // Make a function declaration.
4952 Named_object*
4953 Named_object::make_function_declaration(const std::string& name,
4954 const Package* package,
4955 Function_type* fntype,
4956 Location location)
4958 Named_object* named_object = new Named_object(name, package,
4959 NAMED_OBJECT_FUNC_DECLARATION);
4960 Function_declaration *func_decl = new Function_declaration(fntype, location);
4961 named_object->u_.func_declaration_value = func_decl;
4962 return named_object;
4965 // Make a package.
4967 Named_object*
4968 Named_object::make_package(const std::string& alias, Package* package)
4970 Named_object* named_object = new Named_object(alias, NULL,
4971 NAMED_OBJECT_PACKAGE);
4972 named_object->u_.package_value = package;
4973 return named_object;
4976 // Return the name to use in an error message.
4978 std::string
4979 Named_object::message_name() const
4981 if (this->package_ == NULL)
4982 return Gogo::message_name(this->name_);
4983 std::string ret;
4984 if (this->package_->has_package_name())
4985 ret = this->package_->package_name();
4986 else
4987 ret = this->package_->pkgpath();
4988 ret = Gogo::message_name(ret);
4989 ret += '.';
4990 ret += Gogo::message_name(this->name_);
4991 return ret;
4994 // Set the type when a declaration is defined.
4996 void
4997 Named_object::set_type_value(Named_type* named_type)
4999 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
5000 Type_declaration* td = this->u_.type_declaration;
5001 td->define_methods(named_type);
5002 unsigned int index;
5003 Named_object* in_function = td->in_function(&index);
5004 if (in_function != NULL)
5005 named_type->set_in_function(in_function, index);
5006 delete td;
5007 this->classification_ = NAMED_OBJECT_TYPE;
5008 this->u_.type_value = named_type;
5011 // Define a function which was previously declared.
5013 void
5014 Named_object::set_function_value(Function* function)
5016 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
5017 if (this->func_declaration_value()->has_descriptor())
5019 Expression* descriptor =
5020 this->func_declaration_value()->descriptor(NULL, NULL);
5021 function->set_descriptor(descriptor);
5023 this->classification_ = NAMED_OBJECT_FUNC;
5024 // FIXME: We should free the old value.
5025 this->u_.func_value = function;
5028 // Declare an unknown object as a type declaration.
5030 void
5031 Named_object::declare_as_type()
5033 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
5034 Unknown_name* unk = this->u_.unknown_value;
5035 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
5036 this->u_.type_declaration = new Type_declaration(unk->location());
5037 delete unk;
5040 // Return the location of a named object.
5042 Location
5043 Named_object::location() const
5045 switch (this->classification_)
5047 default:
5048 case NAMED_OBJECT_UNINITIALIZED:
5049 go_unreachable();
5051 case NAMED_OBJECT_ERRONEOUS:
5052 return Linemap::unknown_location();
5054 case NAMED_OBJECT_UNKNOWN:
5055 return this->unknown_value()->location();
5057 case NAMED_OBJECT_CONST:
5058 return this->const_value()->location();
5060 case NAMED_OBJECT_TYPE:
5061 return this->type_value()->location();
5063 case NAMED_OBJECT_TYPE_DECLARATION:
5064 return this->type_declaration_value()->location();
5066 case NAMED_OBJECT_VAR:
5067 return this->var_value()->location();
5069 case NAMED_OBJECT_RESULT_VAR:
5070 return this->result_var_value()->location();
5072 case NAMED_OBJECT_SINK:
5073 go_unreachable();
5075 case NAMED_OBJECT_FUNC:
5076 return this->func_value()->location();
5078 case NAMED_OBJECT_FUNC_DECLARATION:
5079 return this->func_declaration_value()->location();
5081 case NAMED_OBJECT_PACKAGE:
5082 return this->package_value()->location();
5086 // Export a named object.
5088 void
5089 Named_object::export_named_object(Export* exp) const
5091 switch (this->classification_)
5093 default:
5094 case NAMED_OBJECT_UNINITIALIZED:
5095 case NAMED_OBJECT_UNKNOWN:
5096 go_unreachable();
5098 case NAMED_OBJECT_ERRONEOUS:
5099 break;
5101 case NAMED_OBJECT_CONST:
5102 this->const_value()->export_const(exp, this->name_);
5103 break;
5105 case NAMED_OBJECT_TYPE:
5106 this->type_value()->export_named_type(exp, this->name_);
5107 break;
5109 case NAMED_OBJECT_TYPE_DECLARATION:
5110 error_at(this->type_declaration_value()->location(),
5111 "attempt to export %<%s%> which was declared but not defined",
5112 this->message_name().c_str());
5113 break;
5115 case NAMED_OBJECT_FUNC_DECLARATION:
5116 this->func_declaration_value()->export_func(exp, this->name_);
5117 break;
5119 case NAMED_OBJECT_VAR:
5120 this->var_value()->export_var(exp, this->name_);
5121 break;
5123 case NAMED_OBJECT_RESULT_VAR:
5124 case NAMED_OBJECT_SINK:
5125 go_unreachable();
5127 case NAMED_OBJECT_FUNC:
5128 this->func_value()->export_func(exp, this->name_);
5129 break;
5133 // Convert a variable to the backend representation.
5135 Bvariable*
5136 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
5138 if (this->classification_ == NAMED_OBJECT_VAR)
5139 return this->var_value()->get_backend_variable(gogo, function,
5140 this->package_, this->name_);
5141 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
5142 return this->result_var_value()->get_backend_variable(gogo, function,
5143 this->name_);
5144 else
5145 go_unreachable();
5148 // Class Bindings.
5150 Bindings::Bindings(Bindings* enclosing)
5151 : enclosing_(enclosing), named_objects_(), bindings_()
5155 // Clear imports.
5157 void
5158 Bindings::clear_file_scope(Gogo* gogo)
5160 Contour::iterator p = this->bindings_.begin();
5161 while (p != this->bindings_.end())
5163 bool keep;
5164 if (p->second->package() != NULL)
5165 keep = false;
5166 else if (p->second->is_package())
5167 keep = false;
5168 else if (p->second->is_function()
5169 && !p->second->func_value()->type()->is_method()
5170 && Gogo::unpack_hidden_name(p->second->name()) == "init")
5171 keep = false;
5172 else
5173 keep = true;
5175 if (keep)
5176 ++p;
5177 else
5179 gogo->add_file_block_name(p->second->name(), p->second->location());
5180 p = this->bindings_.erase(p);
5185 // Look up a symbol.
5187 Named_object*
5188 Bindings::lookup(const std::string& name) const
5190 Contour::const_iterator p = this->bindings_.find(name);
5191 if (p != this->bindings_.end())
5192 return p->second->resolve();
5193 else if (this->enclosing_ != NULL)
5194 return this->enclosing_->lookup(name);
5195 else
5196 return NULL;
5199 // Look up a symbol locally.
5201 Named_object*
5202 Bindings::lookup_local(const std::string& name) const
5204 Contour::const_iterator p = this->bindings_.find(name);
5205 if (p == this->bindings_.end())
5206 return NULL;
5207 return p->second;
5210 // Remove an object from a set of bindings. This is used for a
5211 // special case in thunks for functions which call recover.
5213 void
5214 Bindings::remove_binding(Named_object* no)
5216 Contour::iterator pb = this->bindings_.find(no->name());
5217 go_assert(pb != this->bindings_.end());
5218 this->bindings_.erase(pb);
5219 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
5220 pn != this->named_objects_.end();
5221 ++pn)
5223 if (*pn == no)
5225 this->named_objects_.erase(pn);
5226 return;
5229 go_unreachable();
5232 // Add a method to the list of objects. This is not added to the
5233 // lookup table. This is so that we have a single list of objects
5234 // declared at the top level, which we walk through when it's time to
5235 // convert to trees.
5237 void
5238 Bindings::add_method(Named_object* method)
5240 this->named_objects_.push_back(method);
5243 // Add a generic Named_object to a Contour.
5245 Named_object*
5246 Bindings::add_named_object_to_contour(Contour* contour,
5247 Named_object* named_object)
5249 go_assert(named_object == named_object->resolve());
5250 const std::string& name(named_object->name());
5251 go_assert(!Gogo::is_sink_name(name));
5253 std::pair<Contour::iterator, bool> ins =
5254 contour->insert(std::make_pair(name, named_object));
5255 if (!ins.second)
5257 // The name was already there.
5258 if (named_object->package() != NULL
5259 && ins.first->second->package() == named_object->package()
5260 && (ins.first->second->classification()
5261 == named_object->classification()))
5263 // This is a second import of the same object.
5264 return ins.first->second;
5266 ins.first->second = this->new_definition(ins.first->second,
5267 named_object);
5268 return ins.first->second;
5270 else
5272 // Don't push declarations on the list. We push them on when
5273 // and if we find the definitions. That way we genericize the
5274 // functions in order.
5275 if (!named_object->is_type_declaration()
5276 && !named_object->is_function_declaration()
5277 && !named_object->is_unknown())
5278 this->named_objects_.push_back(named_object);
5279 return named_object;
5283 // We had an existing named object OLD_OBJECT, and we've seen a new
5284 // one NEW_OBJECT with the same name. FIXME: This does not free the
5285 // new object when we don't need it.
5287 Named_object*
5288 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
5290 if (new_object->is_erroneous() && !old_object->is_erroneous())
5291 return new_object;
5293 std::string reason;
5294 switch (old_object->classification())
5296 default:
5297 case Named_object::NAMED_OBJECT_UNINITIALIZED:
5298 go_unreachable();
5300 case Named_object::NAMED_OBJECT_ERRONEOUS:
5301 return old_object;
5303 case Named_object::NAMED_OBJECT_UNKNOWN:
5305 Named_object* real = old_object->unknown_value()->real_named_object();
5306 if (real != NULL)
5307 return this->new_definition(real, new_object);
5308 go_assert(!new_object->is_unknown());
5309 old_object->unknown_value()->set_real_named_object(new_object);
5310 if (!new_object->is_type_declaration()
5311 && !new_object->is_function_declaration())
5312 this->named_objects_.push_back(new_object);
5313 return new_object;
5316 case Named_object::NAMED_OBJECT_CONST:
5317 break;
5319 case Named_object::NAMED_OBJECT_TYPE:
5320 if (new_object->is_type_declaration())
5321 return old_object;
5322 break;
5324 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5325 if (new_object->is_type_declaration())
5326 return old_object;
5327 if (new_object->is_type())
5329 old_object->set_type_value(new_object->type_value());
5330 new_object->type_value()->set_named_object(old_object);
5331 this->named_objects_.push_back(old_object);
5332 return old_object;
5334 break;
5336 case Named_object::NAMED_OBJECT_VAR:
5337 case Named_object::NAMED_OBJECT_RESULT_VAR:
5338 // We have already given an error in the parser for cases where
5339 // one parameter or result variable redeclares another one.
5340 if ((new_object->is_variable()
5341 && new_object->var_value()->is_parameter())
5342 || new_object->is_result_variable())
5343 return old_object;
5344 break;
5346 case Named_object::NAMED_OBJECT_SINK:
5347 go_unreachable();
5349 case Named_object::NAMED_OBJECT_FUNC:
5350 if (new_object->is_function_declaration())
5352 if (!new_object->func_declaration_value()->asm_name().empty())
5353 sorry("__asm__ for function definitions");
5354 Function_type* old_type = old_object->func_value()->type();
5355 Function_type* new_type =
5356 new_object->func_declaration_value()->type();
5357 if (old_type->is_valid_redeclaration(new_type, &reason))
5358 return old_object;
5360 break;
5362 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5364 Function_type* old_type = old_object->func_declaration_value()->type();
5365 if (new_object->is_function_declaration())
5367 Function_type* new_type =
5368 new_object->func_declaration_value()->type();
5369 if (old_type->is_valid_redeclaration(new_type, &reason))
5370 return old_object;
5372 if (new_object->is_function())
5374 Function_type* new_type = new_object->func_value()->type();
5375 if (old_type->is_valid_redeclaration(new_type, &reason))
5377 if (!old_object->func_declaration_value()->asm_name().empty())
5378 sorry("__asm__ for function definitions");
5379 old_object->set_function_value(new_object->func_value());
5380 this->named_objects_.push_back(old_object);
5381 return old_object;
5385 break;
5387 case Named_object::NAMED_OBJECT_PACKAGE:
5388 break;
5391 std::string n = old_object->message_name();
5392 if (reason.empty())
5393 error_at(new_object->location(), "redefinition of %qs", n.c_str());
5394 else
5395 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
5396 reason.c_str());
5398 inform(old_object->location(), "previous definition of %qs was here",
5399 n.c_str());
5401 return old_object;
5404 // Add a named type.
5406 Named_object*
5407 Bindings::add_named_type(Named_type* named_type)
5409 return this->add_named_object(named_type->named_object());
5412 // Add a function.
5414 Named_object*
5415 Bindings::add_function(const std::string& name, const Package* package,
5416 Function* function)
5418 return this->add_named_object(Named_object::make_function(name, package,
5419 function));
5422 // Add a function declaration.
5424 Named_object*
5425 Bindings::add_function_declaration(const std::string& name,
5426 const Package* package,
5427 Function_type* type,
5428 Location location)
5430 Named_object* no = Named_object::make_function_declaration(name, package,
5431 type, location);
5432 return this->add_named_object(no);
5435 // Define a type which was previously declared.
5437 void
5438 Bindings::define_type(Named_object* no, Named_type* type)
5440 no->set_type_value(type);
5441 this->named_objects_.push_back(no);
5444 // Mark all local variables as used. This is used for some types of
5445 // parse error.
5447 void
5448 Bindings::mark_locals_used()
5450 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
5451 p != this->named_objects_.end();
5452 ++p)
5453 if ((*p)->is_variable())
5454 (*p)->var_value()->set_is_used();
5457 // Traverse bindings.
5460 Bindings::traverse(Traverse* traverse, bool is_global)
5462 unsigned int traverse_mask = traverse->traverse_mask();
5464 // We don't use an iterator because we permit the traversal to add
5465 // new global objects.
5466 const unsigned int e_or_t = (Traverse::traverse_expressions
5467 | Traverse::traverse_types);
5468 const unsigned int e_or_t_or_s = (e_or_t
5469 | Traverse::traverse_statements);
5470 for (size_t i = 0; i < this->named_objects_.size(); ++i)
5472 Named_object* p = this->named_objects_[i];
5473 int t = TRAVERSE_CONTINUE;
5474 switch (p->classification())
5476 case Named_object::NAMED_OBJECT_CONST:
5477 if ((traverse_mask & Traverse::traverse_constants) != 0)
5478 t = traverse->constant(p, is_global);
5479 if (t == TRAVERSE_CONTINUE
5480 && (traverse_mask & e_or_t) != 0)
5482 Type* tc = p->const_value()->type();
5483 if (tc != NULL
5484 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5485 return TRAVERSE_EXIT;
5486 t = p->const_value()->traverse_expression(traverse);
5488 break;
5490 case Named_object::NAMED_OBJECT_VAR:
5491 case Named_object::NAMED_OBJECT_RESULT_VAR:
5492 if ((traverse_mask & Traverse::traverse_variables) != 0)
5493 t = traverse->variable(p);
5494 if (t == TRAVERSE_CONTINUE
5495 && (traverse_mask & e_or_t) != 0)
5497 if (p->is_result_variable()
5498 || p->var_value()->has_type())
5500 Type* tv = (p->is_variable()
5501 ? p->var_value()->type()
5502 : p->result_var_value()->type());
5503 if (tv != NULL
5504 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5505 return TRAVERSE_EXIT;
5508 if (t == TRAVERSE_CONTINUE
5509 && (traverse_mask & e_or_t_or_s) != 0
5510 && p->is_variable())
5511 t = p->var_value()->traverse_expression(traverse, traverse_mask);
5512 break;
5514 case Named_object::NAMED_OBJECT_FUNC:
5515 if ((traverse_mask & Traverse::traverse_functions) != 0)
5516 t = traverse->function(p);
5518 if (t == TRAVERSE_CONTINUE
5519 && (traverse_mask
5520 & (Traverse::traverse_variables
5521 | Traverse::traverse_constants
5522 | Traverse::traverse_functions
5523 | Traverse::traverse_blocks
5524 | Traverse::traverse_statements
5525 | Traverse::traverse_expressions
5526 | Traverse::traverse_types)) != 0)
5527 t = p->func_value()->traverse(traverse);
5528 break;
5530 case Named_object::NAMED_OBJECT_PACKAGE:
5531 // These are traversed in Gogo::traverse.
5532 go_assert(is_global);
5533 break;
5535 case Named_object::NAMED_OBJECT_TYPE:
5536 if ((traverse_mask & e_or_t) != 0)
5537 t = Type::traverse(p->type_value(), traverse);
5538 break;
5540 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5541 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5542 case Named_object::NAMED_OBJECT_UNKNOWN:
5543 case Named_object::NAMED_OBJECT_ERRONEOUS:
5544 break;
5546 case Named_object::NAMED_OBJECT_SINK:
5547 default:
5548 go_unreachable();
5551 if (t == TRAVERSE_EXIT)
5552 return TRAVERSE_EXIT;
5555 // If we need to traverse types, check the function declarations,
5556 // which have types. Also check any methods of a type declaration.
5557 if ((traverse_mask & e_or_t) != 0)
5559 for (Bindings::const_declarations_iterator p =
5560 this->begin_declarations();
5561 p != this->end_declarations();
5562 ++p)
5564 if (p->second->is_function_declaration())
5566 if (Type::traverse(p->second->func_declaration_value()->type(),
5567 traverse)
5568 == TRAVERSE_EXIT)
5569 return TRAVERSE_EXIT;
5571 else if (p->second->is_type_declaration())
5573 const std::vector<Named_object*>* methods =
5574 p->second->type_declaration_value()->methods();
5575 for (std::vector<Named_object*>::const_iterator pm =
5576 methods->begin();
5577 pm != methods->end();
5578 pm++)
5580 Named_object* no = *pm;
5581 Type *t;
5582 if (no->is_function())
5583 t = no->func_value()->type();
5584 else if (no->is_function_declaration())
5585 t = no->func_declaration_value()->type();
5586 else
5587 continue;
5588 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
5589 return TRAVERSE_EXIT;
5595 return TRAVERSE_CONTINUE;
5598 // Class Label.
5600 // Clear any references to this label.
5602 void
5603 Label::clear_refs()
5605 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
5606 p != this->refs_.end();
5607 ++p)
5608 delete *p;
5609 this->refs_.clear();
5612 // Get the backend representation for a label.
5614 Blabel*
5615 Label::get_backend_label(Translate_context* context)
5617 if (this->blabel_ == NULL)
5619 Function* function = context->function()->func_value();
5620 tree fndecl = function->get_decl();
5621 Bfunction* bfunction = tree_to_function(fndecl);
5622 this->blabel_ = context->backend()->label(bfunction, this->name_,
5623 this->location_);
5625 return this->blabel_;
5628 // Return an expression for the address of this label.
5630 Bexpression*
5631 Label::get_addr(Translate_context* context, Location location)
5633 Blabel* label = this->get_backend_label(context);
5634 return context->backend()->label_address(label, location);
5637 // Class Unnamed_label.
5639 // Get the backend representation for an unnamed label.
5641 Blabel*
5642 Unnamed_label::get_blabel(Translate_context* context)
5644 if (this->blabel_ == NULL)
5646 Function* function = context->function()->func_value();
5647 tree fndecl = function->get_decl();
5648 Bfunction* bfunction = tree_to_function(fndecl);
5649 this->blabel_ = context->backend()->label(bfunction, "",
5650 this->location_);
5652 return this->blabel_;
5655 // Return a statement which defines this unnamed label.
5657 Bstatement*
5658 Unnamed_label::get_definition(Translate_context* context)
5660 Blabel* blabel = this->get_blabel(context);
5661 return context->backend()->label_definition_statement(blabel);
5664 // Return a goto statement to this unnamed label.
5666 Bstatement*
5667 Unnamed_label::get_goto(Translate_context* context, Location location)
5669 Blabel* blabel = this->get_blabel(context);
5670 return context->backend()->goto_statement(blabel, location);
5673 // Class Package.
5675 Package::Package(const std::string& pkgpath, Location location)
5676 : pkgpath_(pkgpath), pkgpath_symbol_(Gogo::pkgpath_for_symbol(pkgpath)),
5677 package_name_(), bindings_(new Bindings(NULL)), priority_(0),
5678 location_(location), used_(false), is_imported_(false),
5679 uses_sink_alias_(false)
5681 go_assert(!pkgpath.empty());
5685 // Set the package name.
5687 void
5688 Package::set_package_name(const std::string& package_name, Location location)
5690 go_assert(!package_name.empty());
5691 if (this->package_name_.empty())
5692 this->package_name_ = package_name;
5693 else if (this->package_name_ != package_name)
5694 error_at(location,
5695 "saw two different packages with the same package path %s: %s, %s",
5696 this->pkgpath_.c_str(), this->package_name_.c_str(),
5697 package_name.c_str());
5700 // Set the priority. We may see multiple priorities for an imported
5701 // package; we want to use the largest one.
5703 void
5704 Package::set_priority(int priority)
5706 if (priority > this->priority_)
5707 this->priority_ = priority;
5710 // Determine types of constants. Everything else in a package
5711 // (variables, function declarations) should already have a fixed
5712 // type. Constants may have abstract types.
5714 void
5715 Package::determine_types()
5717 Bindings* bindings = this->bindings_;
5718 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5719 p != bindings->end_definitions();
5720 ++p)
5722 if ((*p)->is_const())
5723 (*p)->const_value()->determine_type();
5727 // Class Traverse.
5729 // Destructor.
5731 Traverse::~Traverse()
5733 if (this->types_seen_ != NULL)
5734 delete this->types_seen_;
5735 if (this->expressions_seen_ != NULL)
5736 delete this->expressions_seen_;
5739 // Record that we are looking at a type, and return true if we have
5740 // already seen it.
5742 bool
5743 Traverse::remember_type(const Type* type)
5745 if (type->is_error_type())
5746 return true;
5747 go_assert((this->traverse_mask() & traverse_types) != 0
5748 || (this->traverse_mask() & traverse_expressions) != 0);
5749 // We mostly only have to remember named types. But it turns out
5750 // that an interface type can refer to itself without using a name
5751 // by relying on interface inheritance, as in
5752 // type I interface { F() interface{I} }
5753 if (type->classification() != Type::TYPE_NAMED
5754 && type->classification() != Type::TYPE_INTERFACE)
5755 return false;
5756 if (this->types_seen_ == NULL)
5757 this->types_seen_ = new Types_seen();
5758 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
5759 return !ins.second;
5762 // Record that we are looking at an expression, and return true if we
5763 // have already seen it.
5765 bool
5766 Traverse::remember_expression(const Expression* expression)
5768 go_assert((this->traverse_mask() & traverse_types) != 0
5769 || (this->traverse_mask() & traverse_expressions) != 0);
5770 if (this->expressions_seen_ == NULL)
5771 this->expressions_seen_ = new Expressions_seen();
5772 std::pair<Expressions_seen::iterator, bool> ins =
5773 this->expressions_seen_->insert(expression);
5774 return !ins.second;
5777 // The default versions of these functions should never be called: the
5778 // traversal mask indicates which functions may be called.
5781 Traverse::variable(Named_object*)
5783 go_unreachable();
5787 Traverse::constant(Named_object*, bool)
5789 go_unreachable();
5793 Traverse::function(Named_object*)
5795 go_unreachable();
5799 Traverse::block(Block*)
5801 go_unreachable();
5805 Traverse::statement(Block*, size_t*, Statement*)
5807 go_unreachable();
5811 Traverse::expression(Expression**)
5813 go_unreachable();
5817 Traverse::type(Type*)
5819 go_unreachable();
5822 // Class Statement_inserter.
5824 void
5825 Statement_inserter::insert(Statement* s)
5827 if (this->block_ != NULL)
5829 go_assert(this->pindex_ != NULL);
5830 this->block_->insert_statement_before(*this->pindex_, s);
5831 ++*this->pindex_;
5833 else if (this->var_ != NULL)
5834 this->var_->add_preinit_statement(this->gogo_, s);
5835 else
5836 go_assert(saw_errors());