Reverting merge from trunk
[official-gcc.git] / gcc / go / gofrontend / gogo.cc
blobeebb75377fae537fa5331f6b5f1d802daeaa1db5
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 an erroneous name that indicates that an error has already
1196 // been reported.
1198 std::string
1199 Gogo::erroneous_name()
1201 static int erroneous_count;
1202 char name[50];
1203 snprintf(name, sizeof name, "$erroneous%d", erroneous_count);
1204 ++erroneous_count;
1205 return name;
1208 // Return whether a name is an erroneous name.
1210 bool
1211 Gogo::is_erroneous_name(const std::string& name)
1213 return name.compare(0, 10, "$erroneous") == 0;
1216 // Return a name for a thunk object.
1218 std::string
1219 Gogo::thunk_name()
1221 static int thunk_count;
1222 char thunk_name[50];
1223 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1224 ++thunk_count;
1225 return thunk_name;
1228 // Return whether a function is a thunk.
1230 bool
1231 Gogo::is_thunk(const Named_object* no)
1233 return no->name().compare(0, 6, "$thunk") == 0;
1236 // Define the global names. We do this only after parsing all the
1237 // input files, because the program might define the global names
1238 // itself.
1240 void
1241 Gogo::define_global_names()
1243 for (Bindings::const_declarations_iterator p =
1244 this->globals_->begin_declarations();
1245 p != this->globals_->end_declarations();
1246 ++p)
1248 Named_object* global_no = p->second;
1249 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1250 Named_object* no = this->package_->bindings()->lookup(name);
1251 if (no == NULL)
1252 continue;
1253 no = no->resolve();
1254 if (no->is_type_declaration())
1256 if (global_no->is_type())
1258 if (no->type_declaration_value()->has_methods())
1259 error_at(no->location(),
1260 "may not define methods for global type");
1261 no->set_type_value(global_no->type_value());
1263 else
1265 error_at(no->location(), "expected type");
1266 Type* errtype = Type::make_error_type();
1267 Named_object* err =
1268 Named_object::make_type("erroneous_type", NULL, errtype,
1269 Linemap::predeclared_location());
1270 no->set_type_value(err->type_value());
1273 else if (no->is_unknown())
1274 no->unknown_value()->set_real_named_object(global_no);
1277 // Give an error if any name is defined in both the package block
1278 // and the file block. For example, this can happen if one file
1279 // imports "fmt" and another file defines a global variable fmt.
1280 for (Bindings::const_declarations_iterator p =
1281 this->package_->bindings()->begin_declarations();
1282 p != this->package_->bindings()->end_declarations();
1283 ++p)
1285 if (p->second->is_unknown()
1286 && p->second->unknown_value()->real_named_object() == NULL)
1288 // No point in warning about an undefined name, as we will
1289 // get other errors later anyhow.
1290 continue;
1292 File_block_names::const_iterator pf =
1293 this->file_block_names_.find(p->second->name());
1294 if (pf != this->file_block_names_.end())
1296 std::string n = p->second->message_name();
1297 error_at(p->second->location(),
1298 "%qs defined as both imported name and global name",
1299 n.c_str());
1300 inform(pf->second, "%qs imported here", n.c_str());
1303 // No package scope identifier may be named "init".
1304 if (!p->second->is_function()
1305 && Gogo::unpack_hidden_name(p->second->name()) == "init")
1307 error_at(p->second->location(),
1308 "cannot declare init - must be func");
1313 // Clear out names in file scope.
1315 void
1316 Gogo::clear_file_scope()
1318 this->package_->bindings()->clear_file_scope(this);
1320 // Warn about packages which were imported but not used.
1321 bool quiet = saw_errors();
1322 for (Packages::iterator p = this->packages_.begin();
1323 p != this->packages_.end();
1324 ++p)
1326 Package* package = p->second;
1327 if (package != this->package_
1328 && package->is_imported()
1329 && !package->used()
1330 && !package->uses_sink_alias()
1331 && !quiet)
1332 error_at(package->location(), "imported and not used: %s",
1333 Gogo::message_name(package->package_name()).c_str());
1334 package->clear_is_imported();
1335 package->clear_uses_sink_alias();
1336 package->clear_used();
1340 // Queue up a type specific function for later writing. These are
1341 // written out in write_specific_type_functions, called after the
1342 // parse tree is lowered.
1344 void
1345 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1346 const std::string& hash_name,
1347 Function_type* hash_fntype,
1348 const std::string& equal_name,
1349 Function_type* equal_fntype)
1351 go_assert(!this->specific_type_functions_are_written_);
1352 go_assert(!this->in_global_scope());
1353 Specific_type_function* tsf = new Specific_type_function(type, name,
1354 hash_name,
1355 hash_fntype,
1356 equal_name,
1357 equal_fntype);
1358 this->specific_type_functions_.push_back(tsf);
1361 // Look for types which need specific hash or equality functions.
1363 class Specific_type_functions : public Traverse
1365 public:
1366 Specific_type_functions(Gogo* gogo)
1367 : Traverse(traverse_types),
1368 gogo_(gogo)
1372 type(Type*);
1374 private:
1375 Gogo* gogo_;
1379 Specific_type_functions::type(Type* t)
1381 Named_object* hash_fn;
1382 Named_object* equal_fn;
1383 switch (t->classification())
1385 case Type::TYPE_NAMED:
1387 Named_type* nt = t->named_type();
1388 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1389 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
1391 // If this is a struct type, we don't want to make functions
1392 // for the unnamed struct.
1393 Type* rt = nt->real_type();
1394 if (rt->struct_type() == NULL)
1396 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1397 return TRAVERSE_EXIT;
1399 else
1401 // If this type is defined in another package, then we don't
1402 // need to worry about the unexported fields.
1403 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
1404 const Struct_field_list* fields = rt->struct_type()->fields();
1405 for (Struct_field_list::const_iterator p = fields->begin();
1406 p != fields->end();
1407 ++p)
1409 if (is_defined_elsewhere
1410 && Gogo::is_hidden_name(p->field_name()))
1411 continue;
1412 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
1413 return TRAVERSE_EXIT;
1417 return TRAVERSE_SKIP_COMPONENTS;
1420 case Type::TYPE_STRUCT:
1421 case Type::TYPE_ARRAY:
1422 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1423 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1424 break;
1426 default:
1427 break;
1430 return TRAVERSE_CONTINUE;
1433 // Write out type specific functions.
1435 void
1436 Gogo::write_specific_type_functions()
1438 Specific_type_functions stf(this);
1439 this->traverse(&stf);
1441 while (!this->specific_type_functions_.empty())
1443 Specific_type_function* tsf = this->specific_type_functions_.back();
1444 this->specific_type_functions_.pop_back();
1445 tsf->type->write_specific_type_functions(this, tsf->name,
1446 tsf->hash_name,
1447 tsf->hash_fntype,
1448 tsf->equal_name,
1449 tsf->equal_fntype);
1450 delete tsf;
1452 this->specific_type_functions_are_written_ = true;
1455 // Traverse the tree.
1457 void
1458 Gogo::traverse(Traverse* traverse)
1460 // Traverse the current package first for consistency. The other
1461 // packages will only contain imported types, constants, and
1462 // declarations.
1463 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1464 return;
1465 for (Packages::const_iterator p = this->packages_.begin();
1466 p != this->packages_.end();
1467 ++p)
1469 if (p->second != this->package_)
1471 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1472 break;
1477 // Add a type to verify. This is used for types of sink variables, in
1478 // order to give appropriate error messages.
1480 void
1481 Gogo::add_type_to_verify(Type* type)
1483 this->verify_types_.push_back(type);
1486 // Traversal class used to verify types.
1488 class Verify_types : public Traverse
1490 public:
1491 Verify_types()
1492 : Traverse(traverse_types)
1496 type(Type*);
1499 // Verify that a type is correct.
1502 Verify_types::type(Type* t)
1504 if (!t->verify())
1505 return TRAVERSE_SKIP_COMPONENTS;
1506 return TRAVERSE_CONTINUE;
1509 // Verify that all types are correct.
1511 void
1512 Gogo::verify_types()
1514 Verify_types traverse;
1515 this->traverse(&traverse);
1517 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
1518 p != this->verify_types_.end();
1519 ++p)
1520 (*p)->verify();
1521 this->verify_types_.clear();
1524 // Traversal class used to lower parse tree.
1526 class Lower_parse_tree : public Traverse
1528 public:
1529 Lower_parse_tree(Gogo* gogo, Named_object* function)
1530 : Traverse(traverse_variables
1531 | traverse_constants
1532 | traverse_functions
1533 | traverse_statements
1534 | traverse_expressions),
1535 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1538 void
1539 set_inserter(const Statement_inserter* inserter)
1540 { this->inserter_ = *inserter; }
1543 variable(Named_object*);
1546 constant(Named_object*, bool);
1549 function(Named_object*);
1552 statement(Block*, size_t* pindex, Statement*);
1555 expression(Expression**);
1557 private:
1558 // General IR.
1559 Gogo* gogo_;
1560 // The function we are traversing.
1561 Named_object* function_;
1562 // Value to use for the predeclared constant iota.
1563 int iota_value_;
1564 // Current statement inserter for use by expressions.
1565 Statement_inserter inserter_;
1568 // Lower variables.
1571 Lower_parse_tree::variable(Named_object* no)
1573 if (!no->is_variable())
1574 return TRAVERSE_CONTINUE;
1576 if (no->is_variable() && no->var_value()->is_global())
1578 // Global variables can have loops in their initialization
1579 // expressions. This is handled in lower_init_expression.
1580 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1581 &this->inserter_);
1582 return TRAVERSE_CONTINUE;
1585 // This is a local variable. We are going to return
1586 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1587 // initialization expression when we reach the variable declaration
1588 // statement. However, that means that we need to traverse the type
1589 // ourselves.
1590 if (no->var_value()->has_type())
1592 Type* type = no->var_value()->type();
1593 if (type != NULL)
1595 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1596 return TRAVERSE_EXIT;
1599 go_assert(!no->var_value()->has_pre_init());
1601 return TRAVERSE_SKIP_COMPONENTS;
1604 // Lower constants. We handle constants specially so that we can set
1605 // the right value for the predeclared constant iota. This works in
1606 // conjunction with the way we lower Const_expression objects.
1609 Lower_parse_tree::constant(Named_object* no, bool)
1611 Named_constant* nc = no->const_value();
1613 // Don't get into trouble if the constant's initializer expression
1614 // refers to the constant itself.
1615 if (nc->lowering())
1616 return TRAVERSE_CONTINUE;
1617 nc->set_lowering();
1619 go_assert(this->iota_value_ == -1);
1620 this->iota_value_ = nc->iota_value();
1621 nc->traverse_expression(this);
1622 this->iota_value_ = -1;
1624 nc->clear_lowering();
1626 // We will traverse the expression a second time, but that will be
1627 // fast.
1629 return TRAVERSE_CONTINUE;
1632 // Lower the body of a function, and set the closure type. Record the
1633 // function while lowering it, so that we can pass it down when
1634 // lowering an expression.
1637 Lower_parse_tree::function(Named_object* no)
1639 no->func_value()->set_closure_type();
1641 go_assert(this->function_ == NULL);
1642 this->function_ = no;
1643 int t = no->func_value()->traverse(this);
1644 this->function_ = NULL;
1646 if (t == TRAVERSE_EXIT)
1647 return t;
1648 return TRAVERSE_SKIP_COMPONENTS;
1651 // Lower statement parse trees.
1654 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1656 // Because we explicitly traverse the statement's contents
1657 // ourselves, we want to skip block statements here. There is
1658 // nothing to lower in a block statement.
1659 if (sorig->is_block_statement())
1660 return TRAVERSE_CONTINUE;
1662 Statement_inserter hold_inserter(this->inserter_);
1663 this->inserter_ = Statement_inserter(block, pindex);
1665 // Lower the expressions first.
1666 int t = sorig->traverse_contents(this);
1667 if (t == TRAVERSE_EXIT)
1669 this->inserter_ = hold_inserter;
1670 return t;
1673 // Keep lowering until nothing changes.
1674 Statement* s = sorig;
1675 while (true)
1677 Statement* snew = s->lower(this->gogo_, this->function_, block,
1678 &this->inserter_);
1679 if (snew == s)
1680 break;
1681 s = snew;
1682 t = s->traverse_contents(this);
1683 if (t == TRAVERSE_EXIT)
1685 this->inserter_ = hold_inserter;
1686 return t;
1690 if (s != sorig)
1691 block->replace_statement(*pindex, s);
1693 this->inserter_ = hold_inserter;
1694 return TRAVERSE_SKIP_COMPONENTS;
1697 // Lower expression parse trees.
1700 Lower_parse_tree::expression(Expression** pexpr)
1702 // We have to lower all subexpressions first, so that we can get
1703 // their type if necessary. This is awkward, because we don't have
1704 // a postorder traversal pass.
1705 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1706 return TRAVERSE_EXIT;
1707 // Keep lowering until nothing changes.
1708 while (true)
1710 Expression* e = *pexpr;
1711 Expression* enew = e->lower(this->gogo_, this->function_,
1712 &this->inserter_, this->iota_value_);
1713 if (enew == e)
1714 break;
1715 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
1716 return TRAVERSE_EXIT;
1717 *pexpr = enew;
1719 return TRAVERSE_SKIP_COMPONENTS;
1722 // Lower the parse tree. This is called after the parse is complete,
1723 // when all names should be resolved.
1725 void
1726 Gogo::lower_parse_tree()
1728 Lower_parse_tree lower_parse_tree(this, NULL);
1729 this->traverse(&lower_parse_tree);
1732 // Lower a block.
1734 void
1735 Gogo::lower_block(Named_object* function, Block* block)
1737 Lower_parse_tree lower_parse_tree(this, function);
1738 block->traverse(&lower_parse_tree);
1741 // Lower an expression. INSERTER may be NULL, in which case the
1742 // expression had better not need to create any temporaries.
1744 void
1745 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1746 Expression** pexpr)
1748 Lower_parse_tree lower_parse_tree(this, function);
1749 if (inserter != NULL)
1750 lower_parse_tree.set_inserter(inserter);
1751 lower_parse_tree.expression(pexpr);
1754 // Lower a constant. This is called when lowering a reference to a
1755 // constant. We have to make sure that the constant has already been
1756 // lowered.
1758 void
1759 Gogo::lower_constant(Named_object* no)
1761 go_assert(no->is_const());
1762 Lower_parse_tree lower(this, NULL);
1763 lower.constant(no, false);
1766 // Traverse the tree to create function descriptors as needed.
1768 class Create_function_descriptors : public Traverse
1770 public:
1771 Create_function_descriptors(Gogo* gogo)
1772 : Traverse(traverse_functions | traverse_expressions),
1773 gogo_(gogo)
1777 function(Named_object*);
1780 expression(Expression**);
1782 private:
1783 Gogo* gogo_;
1786 // Create a descriptor for every top-level exported function.
1789 Create_function_descriptors::function(Named_object* no)
1791 if (no->is_function()
1792 && no->func_value()->enclosing() == NULL
1793 && !no->func_value()->is_method()
1794 && !Gogo::is_hidden_name(no->name())
1795 && !Gogo::is_thunk(no))
1796 no->func_value()->descriptor(this->gogo_, no);
1798 return TRAVERSE_CONTINUE;
1801 // If we see a function referenced in any way other than calling it,
1802 // create a descriptor for it.
1805 Create_function_descriptors::expression(Expression** pexpr)
1807 Expression* expr = *pexpr;
1809 Func_expression* fe = expr->func_expression();
1810 if (fe != NULL)
1812 // We would not get here for a call to this function, so this is
1813 // a reference to a function other than calling it. We need a
1814 // descriptor.
1815 if (fe->closure() != NULL)
1816 return TRAVERSE_CONTINUE;
1817 Named_object* no = fe->named_object();
1818 if (no->is_function() && !no->func_value()->is_method())
1819 no->func_value()->descriptor(this->gogo_, no);
1820 else if (no->is_function_declaration()
1821 && !no->func_declaration_value()->type()->is_method()
1822 && !Linemap::is_predeclared_location(no->location()))
1823 no->func_declaration_value()->descriptor(this->gogo_, no);
1824 return TRAVERSE_CONTINUE;
1827 Bound_method_expression* bme = expr->bound_method_expression();
1828 if (bme != NULL)
1830 // We would not get here for a call to this method, so this is a
1831 // method value. We need to create a thunk.
1832 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
1833 bme->function());
1834 return TRAVERSE_CONTINUE;
1837 Interface_field_reference_expression* ifre =
1838 expr->interface_field_reference_expression();
1839 if (ifre != NULL)
1841 // We would not get here for a call to this interface method, so
1842 // this is a method value. We need to create a thunk.
1843 Interface_type* type = ifre->expr()->type()->interface_type();
1844 if (type != NULL)
1845 Interface_field_reference_expression::create_thunk(this->gogo_, type,
1846 ifre->name());
1847 return TRAVERSE_CONTINUE;
1850 Call_expression* ce = expr->call_expression();
1851 if (ce != NULL)
1853 Expression* fn = ce->fn();
1854 if (fn->func_expression() != NULL
1855 || fn->bound_method_expression() != NULL
1856 || fn->interface_field_reference_expression() != NULL)
1858 // Traverse the arguments but not the function.
1859 Expression_list* args = ce->args();
1860 if (args != NULL)
1862 if (args->traverse(this) == TRAVERSE_EXIT)
1863 return TRAVERSE_EXIT;
1865 return TRAVERSE_SKIP_COMPONENTS;
1869 return TRAVERSE_CONTINUE;
1872 // Create function descriptors as needed. We need a function
1873 // descriptor for all exported functions and for all functions that
1874 // are referenced without being called.
1876 void
1877 Gogo::create_function_descriptors()
1879 // Create a function descriptor for any exported function that is
1880 // declared in this package. This is so that we have a descriptor
1881 // for functions written in assembly. Gather the descriptors first
1882 // so that we don't add declarations while looping over them.
1883 std::vector<Named_object*> fndecls;
1884 Bindings* b = this->package_->bindings();
1885 for (Bindings::const_declarations_iterator p = b->begin_declarations();
1886 p != b->end_declarations();
1887 ++p)
1889 Named_object* no = p->second;
1890 if (no->is_function_declaration()
1891 && !no->func_declaration_value()->type()->is_method()
1892 && !Linemap::is_predeclared_location(no->location())
1893 && !Gogo::is_hidden_name(no->name()))
1894 fndecls.push_back(no);
1896 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
1897 p != fndecls.end();
1898 ++p)
1899 (*p)->func_declaration_value()->descriptor(this, *p);
1900 fndecls.clear();
1902 Create_function_descriptors cfd(this);
1903 this->traverse(&cfd);
1906 // Look for interface types to finalize methods of inherited
1907 // interfaces.
1909 class Finalize_methods : public Traverse
1911 public:
1912 Finalize_methods(Gogo* gogo)
1913 : Traverse(traverse_types),
1914 gogo_(gogo)
1918 type(Type*);
1920 private:
1921 Gogo* gogo_;
1924 // Finalize the methods of an interface type.
1927 Finalize_methods::type(Type* t)
1929 // Check the classification so that we don't finalize the methods
1930 // twice for a named interface type.
1931 switch (t->classification())
1933 case Type::TYPE_INTERFACE:
1934 t->interface_type()->finalize_methods();
1935 break;
1937 case Type::TYPE_NAMED:
1939 // We have to finalize the methods of the real type first.
1940 // But if the real type is a struct type, then we only want to
1941 // finalize the methods of the field types, not of the struct
1942 // type itself. We don't want to add methods to the struct,
1943 // since it has a name.
1944 Named_type* nt = t->named_type();
1945 Type* rt = nt->real_type();
1946 if (rt->classification() != Type::TYPE_STRUCT)
1948 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1949 return TRAVERSE_EXIT;
1951 else
1953 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1954 return TRAVERSE_EXIT;
1957 nt->finalize_methods(this->gogo_);
1959 // If this type is defined in a different package, then finalize the
1960 // types of all the methods, since we won't see them otherwise.
1961 if (nt->named_object()->package() != NULL && nt->has_any_methods())
1963 const Methods* methods = nt->methods();
1964 for (Methods::const_iterator p = methods->begin();
1965 p != methods->end();
1966 ++p)
1968 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1969 return TRAVERSE_EXIT;
1973 // Finalize the types of all methods that are declared but not
1974 // defined, since we won't see the declarations otherwise.
1975 if (nt->named_object()->package() == NULL
1976 && nt->local_methods() != NULL)
1978 const Bindings* methods = nt->local_methods();
1979 for (Bindings::const_declarations_iterator p =
1980 methods->begin_declarations();
1981 p != methods->end_declarations();
1982 p++)
1984 if (p->second->is_function_declaration())
1986 Type* mt = p->second->func_declaration_value()->type();
1987 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
1988 return TRAVERSE_EXIT;
1993 return TRAVERSE_SKIP_COMPONENTS;
1996 case Type::TYPE_STRUCT:
1997 // Traverse the field types first in case there is an embedded
1998 // field with methods that the struct should inherit.
1999 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
2000 return TRAVERSE_EXIT;
2001 t->struct_type()->finalize_methods(this->gogo_);
2002 return TRAVERSE_SKIP_COMPONENTS;
2004 default:
2005 break;
2008 return TRAVERSE_CONTINUE;
2011 // Finalize method lists and build stub methods for types.
2013 void
2014 Gogo::finalize_methods()
2016 Finalize_methods finalize(this);
2017 this->traverse(&finalize);
2020 // Set types for unspecified variables and constants.
2022 void
2023 Gogo::determine_types()
2025 Bindings* bindings = this->current_bindings();
2026 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2027 p != bindings->end_definitions();
2028 ++p)
2030 if ((*p)->is_function())
2031 (*p)->func_value()->determine_types();
2032 else if ((*p)->is_variable())
2033 (*p)->var_value()->determine_type();
2034 else if ((*p)->is_const())
2035 (*p)->const_value()->determine_type();
2037 // See if a variable requires us to build an initialization
2038 // function. We know that we will see all global variables
2039 // here.
2040 if (!this->need_init_fn_ && (*p)->is_variable())
2042 Variable* variable = (*p)->var_value();
2044 // If this is a global variable which requires runtime
2045 // initialization, we need an initialization function.
2046 if (!variable->is_global())
2048 else if (variable->init() == NULL)
2050 else if (variable->type()->interface_type() != NULL)
2051 this->need_init_fn_ = true;
2052 else if (variable->init()->is_constant())
2054 else if (!variable->init()->is_composite_literal())
2055 this->need_init_fn_ = true;
2056 else if (variable->init()->is_nonconstant_composite_literal())
2057 this->need_init_fn_ = true;
2059 // If this is a global variable which holds a pointer value,
2060 // then we need an initialization function to register it as a
2061 // GC root.
2062 if (variable->is_global() && variable->type()->has_pointer())
2063 this->need_init_fn_ = true;
2067 // Determine the types of constants in packages.
2068 for (Packages::const_iterator p = this->packages_.begin();
2069 p != this->packages_.end();
2070 ++p)
2071 p->second->determine_types();
2074 // Traversal class used for type checking.
2076 class Check_types_traverse : public Traverse
2078 public:
2079 Check_types_traverse(Gogo* gogo)
2080 : Traverse(traverse_variables
2081 | traverse_constants
2082 | traverse_functions
2083 | traverse_statements
2084 | traverse_expressions),
2085 gogo_(gogo)
2089 variable(Named_object*);
2092 constant(Named_object*, bool);
2095 function(Named_object*);
2098 statement(Block*, size_t* pindex, Statement*);
2101 expression(Expression**);
2103 private:
2104 // General IR.
2105 Gogo* gogo_;
2108 // Check that a variable initializer has the right type.
2111 Check_types_traverse::variable(Named_object* named_object)
2113 if (named_object->is_variable())
2115 Variable* var = named_object->var_value();
2117 // Give error if variable type is not defined.
2118 var->type()->base();
2120 Expression* init = var->init();
2121 std::string reason;
2122 if (init != NULL
2123 && !Type::are_assignable(var->type(), init->type(), &reason))
2125 if (reason.empty())
2126 error_at(var->location(), "incompatible type in initialization");
2127 else
2128 error_at(var->location(),
2129 "incompatible type in initialization (%s)",
2130 reason.c_str());
2131 var->clear_init();
2133 else if (!var->is_used()
2134 && !var->is_global()
2135 && !var->is_parameter()
2136 && !var->is_receiver()
2137 && !var->type()->is_error()
2138 && (init == NULL || !init->is_error_expression())
2139 && !Lex::is_invalid_identifier(named_object->name()))
2140 error_at(var->location(), "%qs declared and not used",
2141 named_object->message_name().c_str());
2143 return TRAVERSE_CONTINUE;
2146 // Check that a constant initializer has the right type.
2149 Check_types_traverse::constant(Named_object* named_object, bool)
2151 Named_constant* constant = named_object->const_value();
2152 Type* ctype = constant->type();
2153 if (ctype->integer_type() == NULL
2154 && ctype->float_type() == NULL
2155 && ctype->complex_type() == NULL
2156 && !ctype->is_boolean_type()
2157 && !ctype->is_string_type())
2159 if (ctype->is_nil_type())
2160 error_at(constant->location(), "const initializer cannot be nil");
2161 else if (!ctype->is_error())
2162 error_at(constant->location(), "invalid constant type");
2163 constant->set_error();
2165 else if (!constant->expr()->is_constant())
2167 error_at(constant->expr()->location(), "expression is not constant");
2168 constant->set_error();
2170 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
2171 NULL))
2173 error_at(constant->location(),
2174 "initialization expression has wrong type");
2175 constant->set_error();
2177 return TRAVERSE_CONTINUE;
2180 // There are no types to check in a function, but this is where we
2181 // issue warnings about labels which are defined but not referenced.
2184 Check_types_traverse::function(Named_object* no)
2186 no->func_value()->check_labels();
2187 return TRAVERSE_CONTINUE;
2190 // Check that types are valid in a statement.
2193 Check_types_traverse::statement(Block*, size_t*, Statement* s)
2195 s->check_types(this->gogo_);
2196 return TRAVERSE_CONTINUE;
2199 // Check that types are valid in an expression.
2202 Check_types_traverse::expression(Expression** expr)
2204 (*expr)->check_types(this->gogo_);
2205 return TRAVERSE_CONTINUE;
2208 // Check that types are valid.
2210 void
2211 Gogo::check_types()
2213 Check_types_traverse traverse(this);
2214 this->traverse(&traverse);
2217 // Check the types in a single block.
2219 void
2220 Gogo::check_types_in_block(Block* block)
2222 Check_types_traverse traverse(this);
2223 block->traverse(&traverse);
2226 // A traversal class used to find a single shortcut operator within an
2227 // expression.
2229 class Find_shortcut : public Traverse
2231 public:
2232 Find_shortcut()
2233 : Traverse(traverse_blocks
2234 | traverse_statements
2235 | traverse_expressions),
2236 found_(NULL)
2239 // A pointer to the expression which was found, or NULL if none was
2240 // found.
2241 Expression**
2242 found() const
2243 { return this->found_; }
2245 protected:
2247 block(Block*)
2248 { return TRAVERSE_SKIP_COMPONENTS; }
2251 statement(Block*, size_t*, Statement*)
2252 { return TRAVERSE_SKIP_COMPONENTS; }
2255 expression(Expression**);
2257 private:
2258 Expression** found_;
2261 // Find a shortcut expression.
2264 Find_shortcut::expression(Expression** pexpr)
2266 Expression* expr = *pexpr;
2267 Binary_expression* be = expr->binary_expression();
2268 if (be == NULL)
2269 return TRAVERSE_CONTINUE;
2270 Operator op = be->op();
2271 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
2272 return TRAVERSE_CONTINUE;
2273 go_assert(this->found_ == NULL);
2274 this->found_ = pexpr;
2275 return TRAVERSE_EXIT;
2278 // A traversal class used to turn shortcut operators into explicit if
2279 // statements.
2281 class Shortcuts : public Traverse
2283 public:
2284 Shortcuts(Gogo* gogo)
2285 : Traverse(traverse_variables
2286 | traverse_statements),
2287 gogo_(gogo)
2290 protected:
2292 variable(Named_object*);
2295 statement(Block*, size_t*, Statement*);
2297 private:
2298 // Convert a shortcut operator.
2299 Statement*
2300 convert_shortcut(Block* enclosing, Expression** pshortcut);
2302 // The IR.
2303 Gogo* gogo_;
2306 // Remove shortcut operators in a single statement.
2309 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
2311 // FIXME: This approach doesn't work for switch statements, because
2312 // we add the new statements before the whole switch when we need to
2313 // instead add them just before the switch expression. The right
2314 // fix is probably to lower switch statements with nonconstant cases
2315 // to a series of conditionals.
2316 if (s->switch_statement() != NULL)
2317 return TRAVERSE_CONTINUE;
2319 while (true)
2321 Find_shortcut find_shortcut;
2323 // If S is a variable declaration, then ordinary traversal won't
2324 // do anything. We want to explicitly traverse the
2325 // initialization expression if there is one.
2326 Variable_declaration_statement* vds = s->variable_declaration_statement();
2327 Expression* init = NULL;
2328 if (vds == NULL)
2329 s->traverse_contents(&find_shortcut);
2330 else
2332 init = vds->var()->var_value()->init();
2333 if (init == NULL)
2334 return TRAVERSE_CONTINUE;
2335 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(block, pshortcut);
2342 block->insert_statement_before(*pindex, snew);
2343 ++*pindex;
2345 if (pshortcut == &init)
2346 vds->var()->var_value()->set_init(init);
2350 // Remove shortcut operators in the initializer of a global variable.
2353 Shortcuts::variable(Named_object* no)
2355 if (no->is_result_variable())
2356 return TRAVERSE_CONTINUE;
2357 Variable* var = no->var_value();
2358 Expression* init = var->init();
2359 if (!var->is_global() || init == NULL)
2360 return TRAVERSE_CONTINUE;
2362 while (true)
2364 Find_shortcut find_shortcut;
2365 init->traverse(&init, &find_shortcut);
2366 Expression** pshortcut = find_shortcut.found();
2367 if (pshortcut == NULL)
2368 return TRAVERSE_CONTINUE;
2370 Statement* snew = this->convert_shortcut(NULL, pshortcut);
2371 var->add_preinit_statement(this->gogo_, snew);
2372 if (pshortcut == &init)
2373 var->set_init(init);
2377 // Given an expression which uses a shortcut operator, return a
2378 // statement which implements it, and update *PSHORTCUT accordingly.
2380 Statement*
2381 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2383 Binary_expression* shortcut = (*pshortcut)->binary_expression();
2384 Expression* left = shortcut->left();
2385 Expression* right = shortcut->right();
2386 Location loc = shortcut->location();
2388 Block* retblock = new Block(enclosing, loc);
2389 retblock->set_end_location(loc);
2391 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
2392 left, loc);
2393 retblock->add_statement(ts);
2395 Block* block = new Block(retblock, loc);
2396 block->set_end_location(loc);
2397 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2398 Statement* assign = Statement::make_assignment(tmpref, right, loc);
2399 block->add_statement(assign);
2401 Expression* cond = Expression::make_temporary_reference(ts, loc);
2402 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2403 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2405 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2406 loc);
2407 retblock->add_statement(if_statement);
2409 *pshortcut = Expression::make_temporary_reference(ts, loc);
2411 delete shortcut;
2413 // Now convert any shortcut operators in LEFT and RIGHT.
2414 Shortcuts shortcuts(this->gogo_);
2415 retblock->traverse(&shortcuts);
2417 return Statement::make_block_statement(retblock, loc);
2420 // Turn shortcut operators into explicit if statements. Doing this
2421 // considerably simplifies the order of evaluation rules.
2423 void
2424 Gogo::remove_shortcuts()
2426 Shortcuts shortcuts(this);
2427 this->traverse(&shortcuts);
2430 // A traversal class which finds all the expressions which must be
2431 // evaluated in order within a statement or larger expression. This
2432 // is used to implement the rules about order of evaluation.
2434 class Find_eval_ordering : public Traverse
2436 private:
2437 typedef std::vector<Expression**> Expression_pointers;
2439 public:
2440 Find_eval_ordering()
2441 : Traverse(traverse_blocks
2442 | traverse_statements
2443 | traverse_expressions),
2444 exprs_()
2447 size_t
2448 size() const
2449 { return this->exprs_.size(); }
2451 typedef Expression_pointers::const_iterator const_iterator;
2453 const_iterator
2454 begin() const
2455 { return this->exprs_.begin(); }
2457 const_iterator
2458 end() const
2459 { return this->exprs_.end(); }
2461 protected:
2463 block(Block*)
2464 { return TRAVERSE_SKIP_COMPONENTS; }
2467 statement(Block*, size_t*, Statement*)
2468 { return TRAVERSE_SKIP_COMPONENTS; }
2471 expression(Expression**);
2473 private:
2474 // A list of pointers to expressions with side-effects.
2475 Expression_pointers exprs_;
2478 // If an expression must be evaluated in order, put it on the list.
2481 Find_eval_ordering::expression(Expression** expression_pointer)
2483 // We have to look at subexpressions before this one.
2484 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2485 return TRAVERSE_EXIT;
2486 if ((*expression_pointer)->must_eval_in_order())
2487 this->exprs_.push_back(expression_pointer);
2488 return TRAVERSE_SKIP_COMPONENTS;
2491 // A traversal class for ordering evaluations.
2493 class Order_eval : public Traverse
2495 public:
2496 Order_eval(Gogo* gogo)
2497 : Traverse(traverse_variables
2498 | traverse_statements),
2499 gogo_(gogo)
2503 variable(Named_object*);
2506 statement(Block*, size_t*, Statement*);
2508 private:
2509 // The IR.
2510 Gogo* gogo_;
2513 // Implement the order of evaluation rules for a statement.
2516 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2518 // FIXME: This approach doesn't work for switch statements, because
2519 // we add the new statements before the whole switch when we need to
2520 // instead add them just before the switch expression. The right
2521 // fix is probably to lower switch statements with nonconstant cases
2522 // to a series of conditionals.
2523 if (s->switch_statement() != NULL)
2524 return TRAVERSE_CONTINUE;
2526 Find_eval_ordering find_eval_ordering;
2528 // If S is a variable declaration, then ordinary traversal won't do
2529 // anything. We want to explicitly traverse the initialization
2530 // expression if there is one.
2531 Variable_declaration_statement* vds = s->variable_declaration_statement();
2532 Expression* init = NULL;
2533 Expression* orig_init = NULL;
2534 if (vds == NULL)
2535 s->traverse_contents(&find_eval_ordering);
2536 else
2538 init = vds->var()->var_value()->init();
2539 if (init == NULL)
2540 return TRAVERSE_CONTINUE;
2541 orig_init = init;
2543 // It might seem that this could be
2544 // init->traverse_subexpressions. Unfortunately that can fail
2545 // in a case like
2546 // var err os.Error
2547 // newvar, err := call(arg())
2548 // Here newvar will have an init of call result 0 of
2549 // call(arg()). If we only traverse subexpressions, we will
2550 // only find arg(), and we won't bother to move anything out.
2551 // Then we get to the assignment to err, we will traverse the
2552 // whole statement, and this time we will find both call() and
2553 // arg(), and so we will move them out. This will cause them to
2554 // be put into temporary variables before the assignment to err
2555 // but after the declaration of newvar. To avoid that problem,
2556 // we traverse the entire expression here.
2557 Expression::traverse(&init, &find_eval_ordering);
2560 size_t c = find_eval_ordering.size();
2561 if (c == 0)
2562 return TRAVERSE_CONTINUE;
2564 // If there is only one expression with a side-effect, we can
2565 // usually leave it in place.
2566 if (c == 1)
2568 switch (s->classification())
2570 case Statement::STATEMENT_ASSIGNMENT:
2571 // For an assignment statement, we need to evaluate an
2572 // expression on the right hand side before we evaluate any
2573 // index expression on the left hand side, so for that case
2574 // we always move the expression. Otherwise we mishandle
2575 // m[0] = len(m) where m is a map.
2576 break;
2578 case Statement::STATEMENT_EXPRESSION:
2580 // If this is a call statement that doesn't return any
2581 // values, it will not have been counted as a value to
2582 // move. We need to move any subexpressions in case they
2583 // are themselves call statements that require passing a
2584 // closure.
2585 Expression* expr = s->expression_statement()->expr();
2586 if (expr->call_expression() != NULL
2587 && expr->call_expression()->result_count() == 0)
2588 break;
2589 return TRAVERSE_CONTINUE;
2592 default:
2593 // We can leave the expression in place.
2594 return TRAVERSE_CONTINUE;
2598 bool is_thunk = s->thunk_statement() != NULL;
2599 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2600 p != find_eval_ordering.end();
2601 ++p)
2603 Expression** pexpr = *p;
2605 // The last expression in a thunk will be the call passed to go
2606 // or defer, which we must not evaluate early.
2607 if (is_thunk && p + 1 == find_eval_ordering.end())
2608 break;
2610 Location loc = (*pexpr)->location();
2611 Statement* s;
2612 if ((*pexpr)->call_expression() == NULL
2613 || (*pexpr)->call_expression()->result_count() < 2)
2615 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2616 loc);
2617 s = ts;
2618 *pexpr = Expression::make_temporary_reference(ts, loc);
2620 else
2622 // A call expression which returns multiple results needs to
2623 // be handled specially. We can't create a temporary
2624 // because there is no type to give it. Any actual uses of
2625 // the values will be done via Call_result_expressions.
2626 s = Statement::make_statement(*pexpr, true);
2629 block->insert_statement_before(*pindex, s);
2630 ++*pindex;
2633 if (init != orig_init)
2634 vds->var()->var_value()->set_init(init);
2636 return TRAVERSE_CONTINUE;
2639 // Implement the order of evaluation rules for the initializer of a
2640 // global variable.
2643 Order_eval::variable(Named_object* no)
2645 if (no->is_result_variable())
2646 return TRAVERSE_CONTINUE;
2647 Variable* var = no->var_value();
2648 Expression* init = var->init();
2649 if (!var->is_global() || init == NULL)
2650 return TRAVERSE_CONTINUE;
2652 Find_eval_ordering find_eval_ordering;
2653 Expression::traverse(&init, &find_eval_ordering);
2655 if (find_eval_ordering.size() <= 1)
2657 // If there is only one expression with a side-effect, we can
2658 // leave it in place.
2659 return TRAVERSE_SKIP_COMPONENTS;
2662 Expression* orig_init = init;
2664 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2665 p != find_eval_ordering.end();
2666 ++p)
2668 Expression** pexpr = *p;
2669 Location loc = (*pexpr)->location();
2670 Statement* s;
2671 if ((*pexpr)->call_expression() == NULL
2672 || (*pexpr)->call_expression()->result_count() < 2)
2674 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2675 loc);
2676 s = ts;
2677 *pexpr = Expression::make_temporary_reference(ts, loc);
2679 else
2681 // A call expression which returns multiple results needs to
2682 // be handled specially.
2683 s = Statement::make_statement(*pexpr, true);
2685 var->add_preinit_statement(this->gogo_, s);
2688 if (init != orig_init)
2689 var->set_init(init);
2691 return TRAVERSE_SKIP_COMPONENTS;
2694 // Use temporary variables to implement the order of evaluation rules.
2696 void
2697 Gogo::order_evaluations()
2699 Order_eval order_eval(this);
2700 this->traverse(&order_eval);
2703 // Traversal to convert calls to the predeclared recover function to
2704 // pass in an argument indicating whether it can recover from a panic
2705 // or not.
2707 class Convert_recover : public Traverse
2709 public:
2710 Convert_recover(Named_object* arg)
2711 : Traverse(traverse_expressions),
2712 arg_(arg)
2715 protected:
2717 expression(Expression**);
2719 private:
2720 // The argument to pass to the function.
2721 Named_object* arg_;
2724 // Convert calls to recover.
2727 Convert_recover::expression(Expression** pp)
2729 Call_expression* ce = (*pp)->call_expression();
2730 if (ce != NULL && ce->is_recover_call())
2731 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2732 ce->location()));
2733 return TRAVERSE_CONTINUE;
2736 // Traversal for build_recover_thunks.
2738 class Build_recover_thunks : public Traverse
2740 public:
2741 Build_recover_thunks(Gogo* gogo)
2742 : Traverse(traverse_functions),
2743 gogo_(gogo)
2747 function(Named_object*);
2749 private:
2750 Expression*
2751 can_recover_arg(Location);
2753 // General IR.
2754 Gogo* gogo_;
2757 // If this function calls recover, turn it into a thunk.
2760 Build_recover_thunks::function(Named_object* orig_no)
2762 Function* orig_func = orig_no->func_value();
2763 if (!orig_func->calls_recover()
2764 || orig_func->is_recover_thunk()
2765 || orig_func->has_recover_thunk())
2766 return TRAVERSE_CONTINUE;
2768 Gogo* gogo = this->gogo_;
2769 Location location = orig_func->location();
2771 static int count;
2772 char buf[50];
2774 Function_type* orig_fntype = orig_func->type();
2775 Typed_identifier_list* new_params = new Typed_identifier_list();
2776 std::string receiver_name;
2777 if (orig_fntype->is_method())
2779 const Typed_identifier* receiver = orig_fntype->receiver();
2780 snprintf(buf, sizeof buf, "rt.%u", count);
2781 ++count;
2782 receiver_name = buf;
2783 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2784 receiver->location()));
2786 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2787 if (orig_params != NULL && !orig_params->empty())
2789 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2790 p != orig_params->end();
2791 ++p)
2793 snprintf(buf, sizeof buf, "pt.%u", count);
2794 ++count;
2795 new_params->push_back(Typed_identifier(buf, p->type(),
2796 p->location()));
2799 snprintf(buf, sizeof buf, "pr.%u", count);
2800 ++count;
2801 std::string can_recover_name = buf;
2802 new_params->push_back(Typed_identifier(can_recover_name,
2803 Type::lookup_bool_type(),
2804 orig_fntype->location()));
2806 const Typed_identifier_list* orig_results = orig_fntype->results();
2807 Typed_identifier_list* new_results;
2808 if (orig_results == NULL || orig_results->empty())
2809 new_results = NULL;
2810 else
2812 new_results = new Typed_identifier_list();
2813 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2814 p != orig_results->end();
2815 ++p)
2816 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2819 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2820 new_results,
2821 orig_fntype->location());
2822 if (orig_fntype->is_varargs())
2823 new_fntype->set_is_varargs();
2825 std::string name = orig_no->name() + "$recover";
2826 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2827 location);
2828 Function *new_func = new_no->func_value();
2829 if (orig_func->enclosing() != NULL)
2830 new_func->set_enclosing(orig_func->enclosing());
2832 // We build the code for the original function attached to the new
2833 // function, and then swap the original and new function bodies.
2834 // This means that existing references to the original function will
2835 // then refer to the new function. That makes this code a little
2836 // confusing, in that the reference to NEW_NO really refers to the
2837 // other function, not the one we are building.
2839 Expression* closure = NULL;
2840 if (orig_func->needs_closure())
2842 // For the new function we are creating, declare a new parameter
2843 // variable NEW_CLOSURE_NO and set it to be the closure variable
2844 // of the function. This will be set to the closure value
2845 // passed in by the caller. Then pass a reference to this
2846 // variable as the closure value when calling the original
2847 // function. In other words, simply pass the closure value
2848 // through the thunk we are creating.
2849 Named_object* orig_closure_no = orig_func->closure_var();
2850 Variable* orig_closure_var = orig_closure_no->var_value();
2851 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2852 false, false, location);
2853 snprintf(buf, sizeof buf, "closure.%u", count);
2854 ++count;
2855 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2856 new_var);
2857 new_func->set_closure_var(new_closure_no);
2858 closure = Expression::make_var_reference(new_closure_no, location);
2861 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2863 Expression_list* args = new Expression_list();
2864 if (new_params != NULL)
2866 // Note that we skip the last parameter, which is the boolean
2867 // indicating whether recover can succed.
2868 for (Typed_identifier_list::const_iterator p = new_params->begin();
2869 p + 1 != new_params->end();
2870 ++p)
2872 Named_object* p_no = gogo->lookup(p->name(), NULL);
2873 go_assert(p_no != NULL
2874 && p_no->is_variable()
2875 && p_no->var_value()->is_parameter());
2876 args->push_back(Expression::make_var_reference(p_no, location));
2879 args->push_back(this->can_recover_arg(location));
2881 gogo->start_block(location);
2883 Call_expression* call = Expression::make_call(fn, args, false, location);
2885 // Any varargs call has already been lowered.
2886 call->set_varargs_are_lowered();
2888 Statement* s = Statement::make_return_from_call(call, location);
2889 s->determine_types();
2890 gogo->add_statement(s);
2892 Block* b = gogo->finish_block(location);
2894 gogo->add_block(b, location);
2896 // Lower the call in case it returns multiple results.
2897 gogo->lower_block(new_no, b);
2899 gogo->finish_function(location);
2901 // Swap the function bodies and types.
2902 new_func->swap_for_recover(orig_func);
2903 orig_func->set_is_recover_thunk();
2904 new_func->set_calls_recover();
2905 new_func->set_has_recover_thunk();
2907 Bindings* orig_bindings = orig_func->block()->bindings();
2908 Bindings* new_bindings = new_func->block()->bindings();
2909 if (orig_fntype->is_method())
2911 // We changed the receiver to be a regular parameter. We have
2912 // to update the binding accordingly in both functions.
2913 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2914 go_assert(orig_rec_no != NULL
2915 && orig_rec_no->is_variable()
2916 && !orig_rec_no->var_value()->is_receiver());
2917 orig_rec_no->var_value()->set_is_receiver();
2919 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2920 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2921 if (new_rec_no == NULL)
2922 go_assert(saw_errors());
2923 else
2925 go_assert(new_rec_no->is_variable()
2926 && new_rec_no->var_value()->is_receiver());
2927 new_rec_no->var_value()->set_is_not_receiver();
2931 // Because we flipped blocks but not types, the can_recover
2932 // parameter appears in the (now) old bindings as a parameter.
2933 // Change it to a local variable, whereupon it will be discarded.
2934 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2935 go_assert(can_recover_no != NULL
2936 && can_recover_no->is_variable()
2937 && can_recover_no->var_value()->is_parameter());
2938 orig_bindings->remove_binding(can_recover_no);
2940 // Add the can_recover argument to the (now) new bindings, and
2941 // attach it to any recover statements.
2942 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2943 false, true, false, location);
2944 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2945 can_recover_var);
2946 Convert_recover convert_recover(can_recover_no);
2947 new_func->traverse(&convert_recover);
2949 // Update the function pointers in any named results.
2950 new_func->update_result_variables();
2951 orig_func->update_result_variables();
2953 return TRAVERSE_CONTINUE;
2956 // Return the expression to pass for the .can_recover parameter to the
2957 // new function. This indicates whether a call to recover may return
2958 // non-nil. The expression is
2959 // __go_can_recover(__builtin_return_address()).
2961 Expression*
2962 Build_recover_thunks::can_recover_arg(Location location)
2964 static Named_object* builtin_return_address;
2965 if (builtin_return_address == NULL)
2967 const Location bloc = Linemap::predeclared_location();
2969 Typed_identifier_list* param_types = new Typed_identifier_list();
2970 Type* uint_type = Type::lookup_integer_type("uint");
2971 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2973 Typed_identifier_list* return_types = new Typed_identifier_list();
2974 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2975 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2977 Function_type* fntype = Type::make_function_type(NULL, param_types,
2978 return_types, bloc);
2979 builtin_return_address =
2980 Named_object::make_function_declaration("__builtin_return_address",
2981 NULL, fntype, bloc);
2982 const char* n = "__builtin_return_address";
2983 builtin_return_address->func_declaration_value()->set_asm_name(n);
2986 static Named_object* can_recover;
2987 if (can_recover == NULL)
2989 const Location bloc = Linemap::predeclared_location();
2990 Typed_identifier_list* param_types = new Typed_identifier_list();
2991 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2992 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2993 Type* boolean_type = Type::lookup_bool_type();
2994 Typed_identifier_list* results = new Typed_identifier_list();
2995 results->push_back(Typed_identifier("", boolean_type, bloc));
2996 Function_type* fntype = Type::make_function_type(NULL, param_types,
2997 results, bloc);
2998 can_recover = Named_object::make_function_declaration("__go_can_recover",
2999 NULL, fntype,
3000 bloc);
3001 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
3004 Expression* fn = Expression::make_func_reference(builtin_return_address,
3005 NULL, location);
3007 mpz_t zval;
3008 mpz_init_set_ui(zval, 0UL);
3009 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
3010 mpz_clear(zval);
3011 Expression_list *args = new Expression_list();
3012 args->push_back(zexpr);
3014 Expression* call = Expression::make_call(fn, args, false, location);
3016 args = new Expression_list();
3017 args->push_back(call);
3019 fn = Expression::make_func_reference(can_recover, NULL, location);
3020 return Expression::make_call(fn, args, false, location);
3023 // Build thunks for functions which call recover. We build a new
3024 // function with an extra parameter, which is whether a call to
3025 // recover can succeed. We then move the body of this function to
3026 // that one. We then turn this function into a thunk which calls the
3027 // new one, passing the value of
3028 // __go_can_recover(__builtin_return_address()). The function will be
3029 // marked as not splitting the stack. This will cooperate with the
3030 // implementation of defer to make recover do the right thing.
3032 void
3033 Gogo::build_recover_thunks()
3035 Build_recover_thunks build_recover_thunks(this);
3036 this->traverse(&build_recover_thunks);
3039 // Look for named types to see whether we need to create an interface
3040 // method table.
3042 class Build_method_tables : public Traverse
3044 public:
3045 Build_method_tables(Gogo* gogo,
3046 const std::vector<Interface_type*>& interfaces)
3047 : Traverse(traverse_types),
3048 gogo_(gogo), interfaces_(interfaces)
3052 type(Type*);
3054 private:
3055 // The IR.
3056 Gogo* gogo_;
3057 // A list of locally defined interfaces which have hidden methods.
3058 const std::vector<Interface_type*>& interfaces_;
3061 // Build all required interface method tables for types. We need to
3062 // ensure that we have an interface method table for every interface
3063 // which has a hidden method, for every named type which implements
3064 // that interface. Normally we can just build interface method tables
3065 // as we need them. However, in some cases we can require an
3066 // interface method table for an interface defined in a different
3067 // package for a type defined in that package. If that interface and
3068 // type both use a hidden method, that is OK. However, we will not be
3069 // able to build that interface method table when we need it, because
3070 // the type's hidden method will be static. So we have to build it
3071 // here, and just refer it from other packages as needed.
3073 void
3074 Gogo::build_interface_method_tables()
3076 if (saw_errors())
3077 return;
3079 std::vector<Interface_type*> hidden_interfaces;
3080 hidden_interfaces.reserve(this->interface_types_.size());
3081 for (std::vector<Interface_type*>::const_iterator pi =
3082 this->interface_types_.begin();
3083 pi != this->interface_types_.end();
3084 ++pi)
3086 const Typed_identifier_list* methods = (*pi)->methods();
3087 if (methods == NULL)
3088 continue;
3089 for (Typed_identifier_list::const_iterator pm = methods->begin();
3090 pm != methods->end();
3091 ++pm)
3093 if (Gogo::is_hidden_name(pm->name()))
3095 hidden_interfaces.push_back(*pi);
3096 break;
3101 if (!hidden_interfaces.empty())
3103 // Now traverse the tree looking for all named types.
3104 Build_method_tables bmt(this, hidden_interfaces);
3105 this->traverse(&bmt);
3108 // We no longer need the list of interfaces.
3110 this->interface_types_.clear();
3113 // This is called for each type. For a named type, for each of the
3114 // interfaces with hidden methods that it implements, create the
3115 // method table.
3118 Build_method_tables::type(Type* type)
3120 Named_type* nt = type->named_type();
3121 Struct_type* st = type->struct_type();
3122 if (nt != NULL || st != NULL)
3124 for (std::vector<Interface_type*>::const_iterator p =
3125 this->interfaces_.begin();
3126 p != this->interfaces_.end();
3127 ++p)
3129 // We ask whether a pointer to the named type implements the
3130 // interface, because a pointer can implement more methods
3131 // than a value.
3132 if (nt != NULL)
3134 if ((*p)->implements_interface(Type::make_pointer_type(nt),
3135 NULL))
3137 nt->interface_method_table(this->gogo_, *p, false);
3138 nt->interface_method_table(this->gogo_, *p, true);
3141 else
3143 if ((*p)->implements_interface(Type::make_pointer_type(st),
3144 NULL))
3146 st->interface_method_table(this->gogo_, *p, false);
3147 st->interface_method_table(this->gogo_, *p, true);
3152 return TRAVERSE_CONTINUE;
3155 // Traversal class used to check for return statements.
3157 class Check_return_statements_traverse : public Traverse
3159 public:
3160 Check_return_statements_traverse()
3161 : Traverse(traverse_functions)
3165 function(Named_object*);
3168 // Check that a function has a return statement if it needs one.
3171 Check_return_statements_traverse::function(Named_object* no)
3173 Function* func = no->func_value();
3174 const Function_type* fntype = func->type();
3175 const Typed_identifier_list* results = fntype->results();
3177 // We only need a return statement if there is a return value.
3178 if (results == NULL || results->empty())
3179 return TRAVERSE_CONTINUE;
3181 if (func->block()->may_fall_through())
3182 error_at(func->block()->end_location(),
3183 "missing return at end of function");
3185 return TRAVERSE_CONTINUE;
3188 // Check return statements.
3190 void
3191 Gogo::check_return_statements()
3193 Check_return_statements_traverse traverse;
3194 this->traverse(&traverse);
3197 // Work out the package priority. It is one more than the maximum
3198 // priority of an imported package.
3201 Gogo::package_priority() const
3203 int priority = 0;
3204 for (Packages::const_iterator p = this->packages_.begin();
3205 p != this->packages_.end();
3206 ++p)
3207 if (p->second->priority() > priority)
3208 priority = p->second->priority();
3209 return priority + 1;
3212 // Export identifiers as requested.
3214 void
3215 Gogo::do_exports()
3217 // For now we always stream to a section. Later we may want to
3218 // support streaming to a separate file.
3219 Stream_to_section stream;
3221 Export exp(&stream);
3222 exp.register_builtin_types(this);
3223 exp.export_globals(this->package_name(),
3224 this->pkgpath(),
3225 this->package_priority(),
3226 this->imports_,
3227 (this->need_init_fn_ && !this->is_main_package()
3228 ? this->get_init_fn_name()
3229 : ""),
3230 this->imported_init_fns_,
3231 this->package_->bindings());
3234 // Find the blocks in order to convert named types defined in blocks.
3236 class Convert_named_types : public Traverse
3238 public:
3239 Convert_named_types(Gogo* gogo)
3240 : Traverse(traverse_blocks),
3241 gogo_(gogo)
3244 protected:
3246 block(Block* block);
3248 private:
3249 Gogo* gogo_;
3253 Convert_named_types::block(Block* block)
3255 this->gogo_->convert_named_types_in_bindings(block->bindings());
3256 return TRAVERSE_CONTINUE;
3259 // Convert all named types to the backend representation. Since named
3260 // types can refer to other types, this needs to be done in the right
3261 // sequence, which is handled by Named_type::convert. Here we arrange
3262 // to call that for each named type.
3264 void
3265 Gogo::convert_named_types()
3267 this->convert_named_types_in_bindings(this->globals_);
3268 for (Packages::iterator p = this->packages_.begin();
3269 p != this->packages_.end();
3270 ++p)
3272 Package* package = p->second;
3273 this->convert_named_types_in_bindings(package->bindings());
3276 Convert_named_types cnt(this);
3277 this->traverse(&cnt);
3279 // Make all the builtin named types used for type descriptors, and
3280 // then convert them. They will only be written out if they are
3281 // needed.
3282 Type::make_type_descriptor_type();
3283 Type::make_type_descriptor_ptr_type();
3284 Function_type::make_function_type_descriptor_type();
3285 Pointer_type::make_pointer_type_descriptor_type();
3286 Struct_type::make_struct_type_descriptor_type();
3287 Array_type::make_array_type_descriptor_type();
3288 Array_type::make_slice_type_descriptor_type();
3289 Map_type::make_map_type_descriptor_type();
3290 Map_type::make_map_descriptor_type();
3291 Channel_type::make_chan_type_descriptor_type();
3292 Interface_type::make_interface_type_descriptor_type();
3293 Expression::make_func_descriptor_type();
3294 Type::convert_builtin_named_types(this);
3296 Runtime::convert_types(this);
3298 this->named_types_are_converted_ = true;
3301 // Convert all names types in a set of bindings.
3303 void
3304 Gogo::convert_named_types_in_bindings(Bindings* bindings)
3306 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3307 p != bindings->end_definitions();
3308 ++p)
3310 if ((*p)->is_type())
3311 (*p)->type_value()->convert(this);
3315 // Class Function.
3317 Function::Function(Function_type* type, Function* enclosing, Block* block,
3318 Location location)
3319 : type_(type), enclosing_(enclosing), results_(NULL),
3320 closure_var_(NULL), block_(block), location_(location), labels_(),
3321 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
3322 is_sink_(false), results_are_named_(false), nointerface_(false),
3323 is_unnamed_type_stub_method_(false), calls_recover_(false),
3324 is_recover_thunk_(false), has_recover_thunk_(false),
3325 in_unique_section_(false)
3329 // Create the named result variables.
3331 void
3332 Function::create_result_variables(Gogo* gogo)
3334 const Typed_identifier_list* results = this->type_->results();
3335 if (results == NULL || results->empty())
3336 return;
3338 if (!results->front().name().empty())
3339 this->results_are_named_ = true;
3341 this->results_ = new Results();
3342 this->results_->reserve(results->size());
3344 Block* block = this->block_;
3345 int index = 0;
3346 for (Typed_identifier_list::const_iterator p = results->begin();
3347 p != results->end();
3348 ++p, ++index)
3350 std::string name = p->name();
3351 if (name.empty() || Gogo::is_sink_name(name))
3353 static int result_counter;
3354 char buf[100];
3355 snprintf(buf, sizeof buf, "$ret%d", result_counter);
3356 ++result_counter;
3357 name = gogo->pack_hidden_name(buf, false);
3359 Result_variable* result = new Result_variable(p->type(), this, index,
3360 p->location());
3361 Named_object* no = block->bindings()->add_result_variable(name, result);
3362 if (no->is_result_variable())
3363 this->results_->push_back(no);
3364 else
3366 static int dummy_result_count;
3367 char buf[100];
3368 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
3369 ++dummy_result_count;
3370 name = gogo->pack_hidden_name(buf, false);
3371 no = block->bindings()->add_result_variable(name, result);
3372 go_assert(no->is_result_variable());
3373 this->results_->push_back(no);
3378 // Update the named result variables when cloning a function which
3379 // calls recover.
3381 void
3382 Function::update_result_variables()
3384 if (this->results_ == NULL)
3385 return;
3387 for (Results::iterator p = this->results_->begin();
3388 p != this->results_->end();
3389 ++p)
3390 (*p)->result_var_value()->set_function(this);
3393 // Return the closure variable, creating it if necessary.
3395 Named_object*
3396 Function::closure_var()
3398 if (this->closure_var_ == NULL)
3400 go_assert(this->descriptor_ == NULL);
3401 // We don't know the type of the variable yet. We add fields as
3402 // we find them.
3403 Location loc = this->type_->location();
3404 Struct_field_list* sfl = new Struct_field_list;
3405 Type* struct_type = Type::make_struct_type(sfl, loc);
3406 Variable* var = new Variable(Type::make_pointer_type(struct_type),
3407 NULL, false, false, false, loc);
3408 var->set_is_used();
3409 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
3410 // Note that the new variable is not in any binding contour.
3412 return this->closure_var_;
3415 // Set the type of the closure variable.
3417 void
3418 Function::set_closure_type()
3420 if (this->closure_var_ == NULL)
3421 return;
3422 Named_object* closure = this->closure_var_;
3423 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3425 // The first field of a closure is always a pointer to the function
3426 // code.
3427 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
3428 st->push_field(Struct_field(Typed_identifier(".$f", voidptr_type,
3429 this->location_)));
3431 unsigned int index = 1;
3432 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3433 p != this->closure_fields_.end();
3434 ++p, ++index)
3436 Named_object* no = p->first;
3437 char buf[20];
3438 snprintf(buf, sizeof buf, "%u", index);
3439 std::string n = no->name() + buf;
3440 Type* var_type;
3441 if (no->is_variable())
3442 var_type = no->var_value()->type();
3443 else
3444 var_type = no->result_var_value()->type();
3445 Type* field_type = Type::make_pointer_type(var_type);
3446 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3450 // Return whether this function is a method.
3452 bool
3453 Function::is_method() const
3455 return this->type_->is_method();
3458 // Add a label definition.
3460 Label*
3461 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3462 Location location)
3464 Label* lnull = NULL;
3465 std::pair<Labels::iterator, bool> ins =
3466 this->labels_.insert(std::make_pair(label_name, lnull));
3467 Label* label;
3468 if (ins.second)
3470 // This is a new label.
3471 label = new Label(label_name);
3472 ins.first->second = label;
3474 else
3476 // The label was already in the hash table.
3477 label = ins.first->second;
3478 if (label->is_defined())
3480 error_at(location, "label %qs already defined",
3481 Gogo::message_name(label_name).c_str());
3482 inform(label->location(), "previous definition of %qs was here",
3483 Gogo::message_name(label_name).c_str());
3484 return new Label(label_name);
3488 label->define(location, gogo->bindings_snapshot(location));
3490 // Issue any errors appropriate for any previous goto's to this
3491 // label.
3492 const std::vector<Bindings_snapshot*>& refs(label->refs());
3493 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3494 p != refs.end();
3495 ++p)
3496 (*p)->check_goto_to(gogo->current_block());
3497 label->clear_refs();
3499 return label;
3502 // Add a reference to a label.
3504 Label*
3505 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3506 Location location, bool issue_goto_errors)
3508 Label* lnull = NULL;
3509 std::pair<Labels::iterator, bool> ins =
3510 this->labels_.insert(std::make_pair(label_name, lnull));
3511 Label* label;
3512 if (!ins.second)
3514 // The label was already in the hash table.
3515 label = ins.first->second;
3517 else
3519 go_assert(ins.first->second == NULL);
3520 label = new Label(label_name);
3521 ins.first->second = label;
3524 label->set_is_used();
3526 if (issue_goto_errors)
3528 Bindings_snapshot* snapshot = label->snapshot();
3529 if (snapshot != NULL)
3530 snapshot->check_goto_from(gogo->current_block(), location);
3531 else
3532 label->add_snapshot_ref(gogo->bindings_snapshot(location));
3535 return label;
3538 // Warn about labels that are defined but not used.
3540 void
3541 Function::check_labels() const
3543 for (Labels::const_iterator p = this->labels_.begin();
3544 p != this->labels_.end();
3545 p++)
3547 Label* label = p->second;
3548 if (!label->is_used())
3549 error_at(label->location(), "label %qs defined and not used",
3550 Gogo::message_name(label->name()).c_str());
3554 // Swap one function with another. This is used when building the
3555 // thunk we use to call a function which calls recover. It may not
3556 // work for any other case.
3558 void
3559 Function::swap_for_recover(Function *x)
3561 go_assert(this->enclosing_ == x->enclosing_);
3562 std::swap(this->results_, x->results_);
3563 std::swap(this->closure_var_, x->closure_var_);
3564 std::swap(this->block_, x->block_);
3565 go_assert(this->location_ == x->location_);
3566 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3567 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3570 // Traverse the tree.
3573 Function::traverse(Traverse* traverse)
3575 unsigned int traverse_mask = traverse->traverse_mask();
3577 if ((traverse_mask
3578 & (Traverse::traverse_types | Traverse::traverse_expressions))
3579 != 0)
3581 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3582 return TRAVERSE_EXIT;
3585 // FIXME: We should check traverse_functions here if nested
3586 // functions are stored in block bindings.
3587 if (this->block_ != NULL
3588 && (traverse_mask
3589 & (Traverse::traverse_variables
3590 | Traverse::traverse_constants
3591 | Traverse::traverse_blocks
3592 | Traverse::traverse_statements
3593 | Traverse::traverse_expressions
3594 | Traverse::traverse_types)) != 0)
3596 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3597 return TRAVERSE_EXIT;
3600 return TRAVERSE_CONTINUE;
3603 // Work out types for unspecified variables and constants.
3605 void
3606 Function::determine_types()
3608 if (this->block_ != NULL)
3609 this->block_->determine_types();
3612 // Return the function descriptor, the value you get when you refer to
3613 // the function in Go code without calling it.
3615 Expression*
3616 Function::descriptor(Gogo*, Named_object* no)
3618 go_assert(!this->is_method());
3619 go_assert(this->closure_var_ == NULL);
3620 if (this->descriptor_ == NULL)
3621 this->descriptor_ = Expression::make_func_descriptor(no);
3622 return this->descriptor_;
3625 // Get a pointer to the variable representing the defer stack for this
3626 // function, making it if necessary. The value of the variable is set
3627 // by the runtime routines to true if the function is returning,
3628 // rather than panicing through. A pointer to this variable is used
3629 // as a marker for the functions on the defer stack associated with
3630 // this function. A function-specific variable permits inlining a
3631 // function which uses defer.
3633 Expression*
3634 Function::defer_stack(Location location)
3636 if (this->defer_stack_ == NULL)
3638 Type* t = Type::lookup_bool_type();
3639 Expression* n = Expression::make_boolean(false, location);
3640 this->defer_stack_ = Statement::make_temporary(t, n, location);
3641 this->defer_stack_->set_is_address_taken();
3643 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3644 location);
3645 return Expression::make_unary(OPERATOR_AND, ref, location);
3648 // Export the function.
3650 void
3651 Function::export_func(Export* exp, const std::string& name) const
3653 Function::export_func_with_type(exp, name, this->type_);
3656 // Export a function with a type.
3658 void
3659 Function::export_func_with_type(Export* exp, const std::string& name,
3660 const Function_type* fntype)
3662 exp->write_c_string("func ");
3664 if (fntype->is_method())
3666 exp->write_c_string("(");
3667 const Typed_identifier* receiver = fntype->receiver();
3668 exp->write_name(receiver->name());
3669 exp->write_c_string(" ");
3670 exp->write_type(receiver->type());
3671 exp->write_c_string(") ");
3674 exp->write_string(name);
3676 exp->write_c_string(" (");
3677 const Typed_identifier_list* parameters = fntype->parameters();
3678 if (parameters != NULL)
3680 bool is_varargs = fntype->is_varargs();
3681 bool first = true;
3682 for (Typed_identifier_list::const_iterator p = parameters->begin();
3683 p != parameters->end();
3684 ++p)
3686 if (first)
3687 first = false;
3688 else
3689 exp->write_c_string(", ");
3690 exp->write_name(p->name());
3691 exp->write_c_string(" ");
3692 if (!is_varargs || p + 1 != parameters->end())
3693 exp->write_type(p->type());
3694 else
3696 exp->write_c_string("...");
3697 exp->write_type(p->type()->array_type()->element_type());
3701 exp->write_c_string(")");
3703 const Typed_identifier_list* results = fntype->results();
3704 if (results != NULL)
3706 if (results->size() == 1 && results->begin()->name().empty())
3708 exp->write_c_string(" ");
3709 exp->write_type(results->begin()->type());
3711 else
3713 exp->write_c_string(" (");
3714 bool first = true;
3715 for (Typed_identifier_list::const_iterator p = results->begin();
3716 p != results->end();
3717 ++p)
3719 if (first)
3720 first = false;
3721 else
3722 exp->write_c_string(", ");
3723 exp->write_name(p->name());
3724 exp->write_c_string(" ");
3725 exp->write_type(p->type());
3727 exp->write_c_string(")");
3730 exp->write_c_string(";\n");
3733 // Import a function.
3735 void
3736 Function::import_func(Import* imp, std::string* pname,
3737 Typed_identifier** preceiver,
3738 Typed_identifier_list** pparameters,
3739 Typed_identifier_list** presults,
3740 bool* is_varargs)
3742 imp->require_c_string("func ");
3744 *preceiver = NULL;
3745 if (imp->peek_char() == '(')
3747 imp->require_c_string("(");
3748 std::string name = imp->read_name();
3749 imp->require_c_string(" ");
3750 Type* rtype = imp->read_type();
3751 *preceiver = new Typed_identifier(name, rtype, imp->location());
3752 imp->require_c_string(") ");
3755 *pname = imp->read_identifier();
3757 Typed_identifier_list* parameters;
3758 *is_varargs = false;
3759 imp->require_c_string(" (");
3760 if (imp->peek_char() == ')')
3761 parameters = NULL;
3762 else
3764 parameters = new Typed_identifier_list();
3765 while (true)
3767 std::string name = imp->read_name();
3768 imp->require_c_string(" ");
3770 if (imp->match_c_string("..."))
3772 imp->advance(3);
3773 *is_varargs = true;
3776 Type* ptype = imp->read_type();
3777 if (*is_varargs)
3778 ptype = Type::make_array_type(ptype, NULL);
3779 parameters->push_back(Typed_identifier(name, ptype,
3780 imp->location()));
3781 if (imp->peek_char() != ',')
3782 break;
3783 go_assert(!*is_varargs);
3784 imp->require_c_string(", ");
3787 imp->require_c_string(")");
3788 *pparameters = parameters;
3790 Typed_identifier_list* results;
3791 if (imp->peek_char() != ' ')
3792 results = NULL;
3793 else
3795 results = new Typed_identifier_list();
3796 imp->require_c_string(" ");
3797 if (imp->peek_char() != '(')
3799 Type* rtype = imp->read_type();
3800 results->push_back(Typed_identifier("", rtype, imp->location()));
3802 else
3804 imp->require_c_string("(");
3805 while (true)
3807 std::string name = imp->read_name();
3808 imp->require_c_string(" ");
3809 Type* rtype = imp->read_type();
3810 results->push_back(Typed_identifier(name, rtype,
3811 imp->location()));
3812 if (imp->peek_char() != ',')
3813 break;
3814 imp->require_c_string(", ");
3816 imp->require_c_string(")");
3819 imp->require_c_string(";\n");
3820 *presults = results;
3823 // Get the backend representation.
3825 Bfunction*
3826 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
3828 if (this->fndecl_ == NULL)
3830 std::string asm_name;
3831 bool is_visible = false;
3832 if (no->package() != NULL)
3834 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
3836 else if (Gogo::unpack_hidden_name(no->name()) == "init"
3837 && !this->type_->is_method())
3839 else if (Gogo::unpack_hidden_name(no->name()) == "main"
3840 && gogo->is_main_package())
3841 is_visible = true;
3842 // Methods have to be public even if they are hidden because
3843 // they can be pulled into type descriptors when using
3844 // anonymous fields.
3845 else if (!Gogo::is_hidden_name(no->name())
3846 || this->type_->is_method())
3848 if (!this->is_unnamed_type_stub_method_)
3849 is_visible = true;
3850 std::string pkgpath = gogo->pkgpath_symbol();
3851 if (this->type_->is_method()
3852 && Gogo::is_hidden_name(no->name())
3853 && Gogo::hidden_name_pkgpath(no->name()) != gogo->pkgpath())
3855 // This is a method we created for an unexported
3856 // method of an imported embedded type. We need to
3857 // use the pkgpath of the imported package to avoid
3858 // a possible name collision. See bug478 for a test
3859 // case.
3860 pkgpath = Gogo::hidden_name_pkgpath(no->name());
3861 pkgpath = Gogo::pkgpath_for_symbol(pkgpath);
3864 asm_name = pkgpath;
3865 asm_name.append(1, '.');
3866 asm_name.append(Gogo::unpack_hidden_name(no->name()));
3867 if (this->type_->is_method())
3869 asm_name.append(1, '.');
3870 Type* rtype = this->type_->receiver()->type();
3871 asm_name.append(rtype->mangled_name(gogo));
3875 // If a function calls the predeclared recover function, we
3876 // can't inline it, because recover behaves differently in a
3877 // function passed directly to defer. If this is a recover
3878 // thunk that we built to test whether a function can be
3879 // recovered, we can't inline it, because that will mess up
3880 // our return address comparison.
3881 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
3883 // If this is a thunk created to call a function which calls
3884 // the predeclared recover function, we need to disable
3885 // stack splitting for the thunk.
3886 bool disable_split_stack = this->is_recover_thunk_;
3888 Btype* functype = this->type_->get_backend_fntype(gogo);
3889 this->fndecl_ =
3890 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
3891 is_visible, false, is_inlinable,
3892 disable_split_stack,
3893 this->in_unique_section_, this->location());
3895 return this->fndecl_;
3898 // Class Block.
3900 Block::Block(Block* enclosing, Location location)
3901 : enclosing_(enclosing), statements_(),
3902 bindings_(new Bindings(enclosing == NULL
3903 ? NULL
3904 : enclosing->bindings())),
3905 start_location_(location),
3906 end_location_(UNKNOWN_LOCATION)
3910 // Add a statement to a block.
3912 void
3913 Block::add_statement(Statement* statement)
3915 this->statements_.push_back(statement);
3918 // Add a statement to the front of a block. This is slow but is only
3919 // used for reference counts of parameters.
3921 void
3922 Block::add_statement_at_front(Statement* statement)
3924 this->statements_.insert(this->statements_.begin(), statement);
3927 // Replace a statement in a block.
3929 void
3930 Block::replace_statement(size_t index, Statement* s)
3932 go_assert(index < this->statements_.size());
3933 this->statements_[index] = s;
3936 // Add a statement before another statement.
3938 void
3939 Block::insert_statement_before(size_t index, Statement* s)
3941 go_assert(index < this->statements_.size());
3942 this->statements_.insert(this->statements_.begin() + index, s);
3945 // Add a statement after another statement.
3947 void
3948 Block::insert_statement_after(size_t index, Statement* s)
3950 go_assert(index < this->statements_.size());
3951 this->statements_.insert(this->statements_.begin() + index + 1, s);
3954 // Traverse the tree.
3957 Block::traverse(Traverse* traverse)
3959 unsigned int traverse_mask = traverse->traverse_mask();
3961 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3963 int t = traverse->block(this);
3964 if (t == TRAVERSE_EXIT)
3965 return TRAVERSE_EXIT;
3966 else if (t == TRAVERSE_SKIP_COMPONENTS)
3967 return TRAVERSE_CONTINUE;
3970 if ((traverse_mask
3971 & (Traverse::traverse_variables
3972 | Traverse::traverse_constants
3973 | Traverse::traverse_expressions
3974 | Traverse::traverse_types)) != 0)
3976 const unsigned int e_or_t = (Traverse::traverse_expressions
3977 | Traverse::traverse_types);
3978 const unsigned int e_or_t_or_s = (e_or_t
3979 | Traverse::traverse_statements);
3980 for (Bindings::const_definitions_iterator pb =
3981 this->bindings_->begin_definitions();
3982 pb != this->bindings_->end_definitions();
3983 ++pb)
3985 int t = TRAVERSE_CONTINUE;
3986 switch ((*pb)->classification())
3988 case Named_object::NAMED_OBJECT_CONST:
3989 if ((traverse_mask & Traverse::traverse_constants) != 0)
3990 t = traverse->constant(*pb, false);
3991 if (t == TRAVERSE_CONTINUE
3992 && (traverse_mask & e_or_t) != 0)
3994 Type* tc = (*pb)->const_value()->type();
3995 if (tc != NULL
3996 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3997 return TRAVERSE_EXIT;
3998 t = (*pb)->const_value()->traverse_expression(traverse);
4000 break;
4002 case Named_object::NAMED_OBJECT_VAR:
4003 case Named_object::NAMED_OBJECT_RESULT_VAR:
4004 if ((traverse_mask & Traverse::traverse_variables) != 0)
4005 t = traverse->variable(*pb);
4006 if (t == TRAVERSE_CONTINUE
4007 && (traverse_mask & e_or_t) != 0)
4009 if ((*pb)->is_result_variable()
4010 || (*pb)->var_value()->has_type())
4012 Type* tv = ((*pb)->is_variable()
4013 ? (*pb)->var_value()->type()
4014 : (*pb)->result_var_value()->type());
4015 if (tv != NULL
4016 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
4017 return TRAVERSE_EXIT;
4020 if (t == TRAVERSE_CONTINUE
4021 && (traverse_mask & e_or_t_or_s) != 0
4022 && (*pb)->is_variable())
4023 t = (*pb)->var_value()->traverse_expression(traverse,
4024 traverse_mask);
4025 break;
4027 case Named_object::NAMED_OBJECT_FUNC:
4028 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4029 go_unreachable();
4031 case Named_object::NAMED_OBJECT_TYPE:
4032 if ((traverse_mask & e_or_t) != 0)
4033 t = Type::traverse((*pb)->type_value(), traverse);
4034 break;
4036 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4037 case Named_object::NAMED_OBJECT_UNKNOWN:
4038 case Named_object::NAMED_OBJECT_ERRONEOUS:
4039 break;
4041 case Named_object::NAMED_OBJECT_PACKAGE:
4042 case Named_object::NAMED_OBJECT_SINK:
4043 go_unreachable();
4045 default:
4046 go_unreachable();
4049 if (t == TRAVERSE_EXIT)
4050 return TRAVERSE_EXIT;
4054 // No point in checking traverse_mask here--if we got here we always
4055 // want to walk the statements. The traversal can insert new
4056 // statements before or after the current statement. Inserting
4057 // statements before the current statement requires updating I via
4058 // the pointer; those statements will not be traversed. Any new
4059 // statements inserted after the current statement will be traversed
4060 // in their turn.
4061 for (size_t i = 0; i < this->statements_.size(); ++i)
4063 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
4064 return TRAVERSE_EXIT;
4067 return TRAVERSE_CONTINUE;
4070 // Work out types for unspecified variables and constants.
4072 void
4073 Block::determine_types()
4075 for (Bindings::const_definitions_iterator pb =
4076 this->bindings_->begin_definitions();
4077 pb != this->bindings_->end_definitions();
4078 ++pb)
4080 if ((*pb)->is_variable())
4081 (*pb)->var_value()->determine_type();
4082 else if ((*pb)->is_const())
4083 (*pb)->const_value()->determine_type();
4086 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
4087 ps != this->statements_.end();
4088 ++ps)
4089 (*ps)->determine_types();
4092 // Return true if the statements in this block may fall through.
4094 bool
4095 Block::may_fall_through() const
4097 if (this->statements_.empty())
4098 return true;
4099 return this->statements_.back()->may_fall_through();
4102 // Convert a block to the backend representation.
4104 Bblock*
4105 Block::get_backend(Translate_context* context)
4107 Gogo* gogo = context->gogo();
4108 Named_object* function = context->function();
4109 std::vector<Bvariable*> vars;
4110 vars.reserve(this->bindings_->size_definitions());
4111 for (Bindings::const_definitions_iterator pv =
4112 this->bindings_->begin_definitions();
4113 pv != this->bindings_->end_definitions();
4114 ++pv)
4116 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
4117 vars.push_back((*pv)->get_backend_variable(gogo, function));
4120 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
4121 // until we have a proper representation of the init function.
4122 Bfunction* bfunction;
4123 if (function == NULL)
4124 bfunction = NULL;
4125 else
4126 bfunction = tree_to_function(function->func_value()->get_decl());
4127 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
4128 vars, this->start_location_,
4129 this->end_location_);
4131 Translate_context subcontext(gogo, function, this, ret);
4132 std::vector<Bstatement*> bstatements;
4133 bstatements.reserve(this->statements_.size());
4134 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
4135 p != this->statements_.end();
4136 ++p)
4137 bstatements.push_back((*p)->get_backend(&subcontext));
4139 context->backend()->block_add_statements(ret, bstatements);
4141 return ret;
4144 // Class Bindings_snapshot.
4146 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
4147 : block_(b), counts_(), location_(location)
4149 while (b != NULL)
4151 this->counts_.push_back(b->bindings()->size_definitions());
4152 b = b->enclosing();
4156 // Report errors appropriate for a goto from B to this.
4158 void
4159 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
4161 size_t dummy;
4162 if (!this->check_goto_block(loc, b, this->block_, &dummy))
4163 return;
4164 this->check_goto_defs(loc, this->block_,
4165 this->block_->bindings()->size_definitions(),
4166 this->counts_[0]);
4169 // Report errors appropriate for a goto from this to B.
4171 void
4172 Bindings_snapshot::check_goto_to(const Block* b)
4174 size_t index;
4175 if (!this->check_goto_block(this->location_, this->block_, b, &index))
4176 return;
4177 this->check_goto_defs(this->location_, b, this->counts_[index],
4178 b->bindings()->size_definitions());
4181 // Report errors appropriate for a goto at LOC from BFROM to BTO.
4182 // Return true if all is well, false if we reported an error. If this
4183 // returns true, it sets *PINDEX to the number of blocks BTO is above
4184 // BFROM.
4186 bool
4187 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
4188 const Block* bto, size_t* pindex)
4190 // It is an error if BTO is not either BFROM or above BFROM.
4191 size_t index = 0;
4192 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
4194 if (pb == NULL)
4196 error_at(loc, "goto jumps into block");
4197 inform(bto->start_location(), "goto target block starts here");
4198 return false;
4201 *pindex = index;
4202 return true;
4205 // Report errors appropriate for a goto at LOC ending at BLOCK, where
4206 // CFROM is the number of names defined at the point of the goto and
4207 // CTO is the number of names defined at the point of the label.
4209 void
4210 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
4211 size_t cfrom, size_t cto)
4213 if (cfrom < cto)
4215 Bindings::const_definitions_iterator p =
4216 block->bindings()->begin_definitions();
4217 for (size_t i = 0; i < cfrom; ++i)
4219 go_assert(p != block->bindings()->end_definitions());
4220 ++p;
4222 go_assert(p != block->bindings()->end_definitions());
4224 std::string n = (*p)->message_name();
4225 error_at(loc, "goto jumps over declaration of %qs", n.c_str());
4226 inform((*p)->location(), "%qs defined here", n.c_str());
4230 // Class Function_declaration.
4232 // Return the function descriptor.
4234 Expression*
4235 Function_declaration::descriptor(Gogo*, Named_object* no)
4237 go_assert(!this->fntype_->is_method());
4238 if (this->descriptor_ == NULL)
4239 this->descriptor_ = Expression::make_func_descriptor(no);
4240 return this->descriptor_;
4243 // Class Variable.
4245 Variable::Variable(Type* type, Expression* init, bool is_global,
4246 bool is_parameter, bool is_receiver,
4247 Location location)
4248 : type_(type), init_(init), preinit_(NULL), location_(location),
4249 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
4250 is_receiver_(is_receiver), is_varargs_parameter_(false), is_used_(false),
4251 is_address_taken_(false), is_non_escaping_address_taken_(false),
4252 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
4253 type_from_range_index_(false), type_from_range_value_(false),
4254 type_from_chan_element_(false), is_type_switch_var_(false),
4255 determined_type_(false), in_unique_section_(false)
4257 go_assert(type != NULL || init != NULL);
4258 go_assert(!is_parameter || init == NULL);
4261 // Traverse the initializer expression.
4264 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
4266 if (this->preinit_ != NULL)
4268 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
4269 return TRAVERSE_EXIT;
4271 if (this->init_ != NULL
4272 && ((traverse_mask
4273 & (Traverse::traverse_expressions | Traverse::traverse_types))
4274 != 0))
4276 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
4277 return TRAVERSE_EXIT;
4279 return TRAVERSE_CONTINUE;
4282 // Lower the initialization expression after parsing is complete.
4284 void
4285 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
4286 Statement_inserter* inserter)
4288 Named_object* dep = gogo->var_depends_on(this);
4289 if (dep != NULL && dep->is_variable())
4290 dep->var_value()->lower_init_expression(gogo, function, inserter);
4292 if (this->init_ != NULL && !this->init_is_lowered_)
4294 if (this->seen_)
4296 // We will give an error elsewhere, this is just to prevent
4297 // an infinite loop.
4298 return;
4300 this->seen_ = true;
4302 Statement_inserter global_inserter;
4303 if (this->is_global_)
4305 global_inserter = Statement_inserter(gogo, this);
4306 inserter = &global_inserter;
4309 gogo->lower_expression(function, inserter, &this->init_);
4311 this->seen_ = false;
4313 this->init_is_lowered_ = true;
4317 // Get the preinit block.
4319 Block*
4320 Variable::preinit_block(Gogo* gogo)
4322 go_assert(this->is_global_);
4323 if (this->preinit_ == NULL)
4324 this->preinit_ = new Block(NULL, this->location());
4326 // If a global variable has a preinitialization statement, then we
4327 // need to have an initialization function.
4328 gogo->set_need_init_fn();
4330 return this->preinit_;
4333 // Add a statement to be run before the initialization expression.
4335 void
4336 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
4338 Block* b = this->preinit_block(gogo);
4339 b->add_statement(s);
4340 b->set_end_location(s->location());
4343 // Whether this variable has a type.
4345 bool
4346 Variable::has_type() const
4348 if (this->type_ == NULL)
4349 return false;
4351 // A variable created in a type switch case nil does not actually
4352 // have a type yet. It will be changed to use the initializer's
4353 // type in determine_type.
4354 if (this->is_type_switch_var_
4355 && this->type_->is_nil_constant_as_type())
4356 return false;
4358 return true;
4361 // In an assignment which sets a variable to a tuple of EXPR, return
4362 // the type of the first element of the tuple.
4364 Type*
4365 Variable::type_from_tuple(Expression* expr, bool report_error) const
4367 if (expr->map_index_expression() != NULL)
4369 Map_type* mt = expr->map_index_expression()->get_map_type();
4370 if (mt == NULL)
4371 return Type::make_error_type();
4372 return mt->val_type();
4374 else if (expr->receive_expression() != NULL)
4376 Expression* channel = expr->receive_expression()->channel();
4377 Type* channel_type = channel->type();
4378 if (channel_type->channel_type() == NULL)
4379 return Type::make_error_type();
4380 return channel_type->channel_type()->element_type();
4382 else
4384 if (report_error)
4385 error_at(this->location(), "invalid tuple definition");
4386 return Type::make_error_type();
4390 // Given EXPR used in a range clause, return either the index type or
4391 // the value type of the range, depending upon GET_INDEX_TYPE.
4393 Type*
4394 Variable::type_from_range(Expression* expr, bool get_index_type,
4395 bool report_error) const
4397 Type* t = expr->type();
4398 if (t->array_type() != NULL
4399 || (t->points_to() != NULL
4400 && t->points_to()->array_type() != NULL
4401 && !t->points_to()->is_slice_type()))
4403 if (get_index_type)
4404 return Type::lookup_integer_type("int");
4405 else
4406 return t->deref()->array_type()->element_type();
4408 else if (t->is_string_type())
4410 if (get_index_type)
4411 return Type::lookup_integer_type("int");
4412 else
4413 return Type::lookup_integer_type("int32");
4415 else if (t->map_type() != NULL)
4417 if (get_index_type)
4418 return t->map_type()->key_type();
4419 else
4420 return t->map_type()->val_type();
4422 else if (t->channel_type() != NULL)
4424 if (get_index_type)
4425 return t->channel_type()->element_type();
4426 else
4428 if (report_error)
4429 error_at(this->location(),
4430 "invalid definition of value variable for channel range");
4431 return Type::make_error_type();
4434 else
4436 if (report_error)
4437 error_at(this->location(), "invalid type for range clause");
4438 return Type::make_error_type();
4442 // EXPR should be a channel. Return the channel's element type.
4444 Type*
4445 Variable::type_from_chan_element(Expression* expr, bool report_error) const
4447 Type* t = expr->type();
4448 if (t->channel_type() != NULL)
4449 return t->channel_type()->element_type();
4450 else
4452 if (report_error)
4453 error_at(this->location(), "expected channel");
4454 return Type::make_error_type();
4458 // Return the type of the Variable. This may be called before
4459 // Variable::determine_type is called, which means that we may need to
4460 // get the type from the initializer. FIXME: If we combine lowering
4461 // with type determination, then this should be unnecessary.
4463 Type*
4464 Variable::type()
4466 // A variable in a type switch with a nil case will have the wrong
4467 // type here. This gets fixed up in determine_type, below.
4468 Type* type = this->type_;
4469 Expression* init = this->init_;
4470 if (this->is_type_switch_var_
4471 && this->type_->is_nil_constant_as_type())
4473 Type_guard_expression* tge = this->init_->type_guard_expression();
4474 go_assert(tge != NULL);
4475 init = tge->expr();
4476 type = NULL;
4479 if (this->seen_)
4481 if (this->type_ == NULL || !this->type_->is_error_type())
4483 error_at(this->location_, "variable initializer refers to itself");
4484 this->type_ = Type::make_error_type();
4486 return this->type_;
4489 this->seen_ = true;
4491 if (type != NULL)
4493 else if (this->type_from_init_tuple_)
4494 type = this->type_from_tuple(init, false);
4495 else if (this->type_from_range_index_ || this->type_from_range_value_)
4496 type = this->type_from_range(init, this->type_from_range_index_, false);
4497 else if (this->type_from_chan_element_)
4498 type = this->type_from_chan_element(init, false);
4499 else
4501 go_assert(init != NULL);
4502 type = init->type();
4503 go_assert(type != NULL);
4505 // Variables should not have abstract types.
4506 if (type->is_abstract())
4507 type = type->make_non_abstract_type();
4509 if (type->is_void_type())
4510 type = Type::make_error_type();
4513 this->seen_ = false;
4515 return type;
4518 // Fetch the type from a const pointer, in which case it should have
4519 // been set already.
4521 Type*
4522 Variable::type() const
4524 go_assert(this->type_ != NULL);
4525 return this->type_;
4528 // Set the type if necessary.
4530 void
4531 Variable::determine_type()
4533 if (this->determined_type_)
4534 return;
4535 this->determined_type_ = true;
4537 if (this->preinit_ != NULL)
4538 this->preinit_->determine_types();
4540 // A variable in a type switch with a nil case will have the wrong
4541 // type here. It will have an initializer which is a type guard.
4542 // We want to initialize it to the value without the type guard, and
4543 // use the type of that value as well.
4544 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
4546 Type_guard_expression* tge = this->init_->type_guard_expression();
4547 go_assert(tge != NULL);
4548 this->type_ = NULL;
4549 this->init_ = tge->expr();
4552 if (this->init_ == NULL)
4553 go_assert(this->type_ != NULL && !this->type_->is_abstract());
4554 else if (this->type_from_init_tuple_)
4556 Expression *init = this->init_;
4557 init->determine_type_no_context();
4558 this->type_ = this->type_from_tuple(init, true);
4559 this->init_ = NULL;
4561 else if (this->type_from_range_index_ || this->type_from_range_value_)
4563 Expression* init = this->init_;
4564 init->determine_type_no_context();
4565 this->type_ = this->type_from_range(init, this->type_from_range_index_,
4566 true);
4567 this->init_ = NULL;
4569 else if (this->type_from_chan_element_)
4571 Expression* init = this->init_;
4572 init->determine_type_no_context();
4573 this->type_ = this->type_from_chan_element(init, true);
4574 this->init_ = NULL;
4576 else
4578 Type_context context(this->type_, false);
4579 this->init_->determine_type(&context);
4580 if (this->type_ == NULL)
4582 Type* type = this->init_->type();
4583 go_assert(type != NULL);
4584 if (type->is_abstract())
4585 type = type->make_non_abstract_type();
4587 if (type->is_void_type())
4589 error_at(this->location_, "variable has no type");
4590 type = Type::make_error_type();
4592 else if (type->is_nil_type())
4594 error_at(this->location_, "variable defined to nil type");
4595 type = Type::make_error_type();
4597 else if (type->is_call_multiple_result_type())
4599 error_at(this->location_,
4600 "single variable set to multiple-value function call");
4601 type = Type::make_error_type();
4604 this->type_ = type;
4609 // Export the variable
4611 void
4612 Variable::export_var(Export* exp, const std::string& name) const
4614 go_assert(this->is_global_);
4615 exp->write_c_string("var ");
4616 exp->write_string(name);
4617 exp->write_c_string(" ");
4618 exp->write_type(this->type());
4619 exp->write_c_string(";\n");
4622 // Import a variable.
4624 void
4625 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
4627 imp->require_c_string("var ");
4628 *pname = imp->read_identifier();
4629 imp->require_c_string(" ");
4630 *ptype = imp->read_type();
4631 imp->require_c_string(";\n");
4634 // Convert a variable to the backend representation.
4636 Bvariable*
4637 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
4638 const Package* package, const std::string& name)
4640 if (this->backend_ == NULL)
4642 Backend* backend = gogo->backend();
4643 Type* type = this->type_;
4644 if (type->is_error_type()
4645 || (type->is_undefined()
4646 && (!this->is_global_ || package == NULL)))
4647 this->backend_ = backend->error_variable();
4648 else
4650 bool is_parameter = this->is_parameter_;
4651 if (this->is_receiver_ && type->points_to() == NULL)
4652 is_parameter = false;
4653 if (this->is_in_heap())
4655 is_parameter = false;
4656 type = Type::make_pointer_type(type);
4659 std::string n = Gogo::unpack_hidden_name(name);
4660 Btype* btype = type->get_backend(gogo);
4662 Bvariable* bvar;
4663 if (this->is_global_)
4664 bvar = backend->global_variable((package == NULL
4665 ? gogo->package_name()
4666 : package->package_name()),
4667 (package == NULL
4668 ? gogo->pkgpath_symbol()
4669 : package->pkgpath_symbol()),
4671 btype,
4672 package != NULL,
4673 Gogo::is_hidden_name(name),
4674 this->in_unique_section_,
4675 this->location_);
4676 else if (function == NULL)
4678 go_assert(saw_errors());
4679 bvar = backend->error_variable();
4681 else
4683 tree fndecl = function->func_value()->get_decl();
4684 Bfunction* bfunction = tree_to_function(fndecl);
4685 bool is_address_taken = (this->is_non_escaping_address_taken_
4686 && !this->is_in_heap());
4687 if (is_parameter)
4688 bvar = backend->parameter_variable(bfunction, n, btype,
4689 is_address_taken,
4690 this->location_);
4691 else
4692 bvar = backend->local_variable(bfunction, n, btype,
4693 is_address_taken,
4694 this->location_);
4696 this->backend_ = bvar;
4699 return this->backend_;
4702 // Class Result_variable.
4704 // Convert a result variable to the backend representation.
4706 Bvariable*
4707 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
4708 const std::string& name)
4710 if (this->backend_ == NULL)
4712 Backend* backend = gogo->backend();
4713 Type* type = this->type_;
4714 if (type->is_error())
4715 this->backend_ = backend->error_variable();
4716 else
4718 if (this->is_in_heap())
4719 type = Type::make_pointer_type(type);
4720 Btype* btype = type->get_backend(gogo);
4721 tree fndecl = function->func_value()->get_decl();
4722 Bfunction* bfunction = tree_to_function(fndecl);
4723 std::string n = Gogo::unpack_hidden_name(name);
4724 bool is_address_taken = (this->is_non_escaping_address_taken_
4725 && !this->is_in_heap());
4726 this->backend_ = backend->local_variable(bfunction, n, btype,
4727 is_address_taken,
4728 this->location_);
4731 return this->backend_;
4734 // Class Named_constant.
4736 // Traverse the initializer expression.
4739 Named_constant::traverse_expression(Traverse* traverse)
4741 return Expression::traverse(&this->expr_, traverse);
4744 // Determine the type of the constant.
4746 void
4747 Named_constant::determine_type()
4749 if (this->type_ != NULL)
4751 Type_context context(this->type_, false);
4752 this->expr_->determine_type(&context);
4754 else
4756 // A constant may have an abstract type.
4757 Type_context context(NULL, true);
4758 this->expr_->determine_type(&context);
4759 this->type_ = this->expr_->type();
4760 go_assert(this->type_ != NULL);
4764 // Indicate that we found and reported an error for this constant.
4766 void
4767 Named_constant::set_error()
4769 this->type_ = Type::make_error_type();
4770 this->expr_ = Expression::make_error(this->location_);
4773 // Export a constant.
4775 void
4776 Named_constant::export_const(Export* exp, const std::string& name) const
4778 exp->write_c_string("const ");
4779 exp->write_string(name);
4780 exp->write_c_string(" ");
4781 if (!this->type_->is_abstract())
4783 exp->write_type(this->type_);
4784 exp->write_c_string(" ");
4786 exp->write_c_string("= ");
4787 this->expr()->export_expression(exp);
4788 exp->write_c_string(";\n");
4791 // Import a constant.
4793 void
4794 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
4795 Expression** pexpr)
4797 imp->require_c_string("const ");
4798 *pname = imp->read_identifier();
4799 imp->require_c_string(" ");
4800 if (imp->peek_char() == '=')
4801 *ptype = NULL;
4802 else
4804 *ptype = imp->read_type();
4805 imp->require_c_string(" ");
4807 imp->require_c_string("= ");
4808 *pexpr = Expression::import_expression(imp);
4809 imp->require_c_string(";\n");
4812 // Add a method.
4814 Named_object*
4815 Type_declaration::add_method(const std::string& name, Function* function)
4817 Named_object* ret = Named_object::make_function(name, NULL, function);
4818 this->methods_.push_back(ret);
4819 return ret;
4822 // Add a method declaration.
4824 Named_object*
4825 Type_declaration::add_method_declaration(const std::string& name,
4826 Package* package,
4827 Function_type* type,
4828 Location location)
4830 Named_object* ret = Named_object::make_function_declaration(name, package,
4831 type, location);
4832 this->methods_.push_back(ret);
4833 return ret;
4836 // Return whether any methods ere defined.
4838 bool
4839 Type_declaration::has_methods() const
4841 return !this->methods_.empty();
4844 // Define methods for the real type.
4846 void
4847 Type_declaration::define_methods(Named_type* nt)
4849 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
4850 p != this->methods_.end();
4851 ++p)
4852 nt->add_existing_method(*p);
4855 // We are using the type. Return true if we should issue a warning.
4857 bool
4858 Type_declaration::using_type()
4860 bool ret = !this->issued_warning_;
4861 this->issued_warning_ = true;
4862 return ret;
4865 // Class Unknown_name.
4867 // Set the real named object.
4869 void
4870 Unknown_name::set_real_named_object(Named_object* no)
4872 go_assert(this->real_named_object_ == NULL);
4873 go_assert(!no->is_unknown());
4874 this->real_named_object_ = no;
4877 // Class Named_object.
4879 Named_object::Named_object(const std::string& name,
4880 const Package* package,
4881 Classification classification)
4882 : name_(name), package_(package), classification_(classification),
4883 tree_(NULL)
4885 if (Gogo::is_sink_name(name))
4886 go_assert(classification == NAMED_OBJECT_SINK);
4889 // Make an unknown name. This is used by the parser. The name must
4890 // be resolved later. Unknown names are only added in the current
4891 // package.
4893 Named_object*
4894 Named_object::make_unknown_name(const std::string& name,
4895 Location location)
4897 Named_object* named_object = new Named_object(name, NULL,
4898 NAMED_OBJECT_UNKNOWN);
4899 Unknown_name* value = new Unknown_name(location);
4900 named_object->u_.unknown_value = value;
4901 return named_object;
4904 // Make a constant.
4906 Named_object*
4907 Named_object::make_constant(const Typed_identifier& tid,
4908 const Package* package, Expression* expr,
4909 int iota_value)
4911 Named_object* named_object = new Named_object(tid.name(), package,
4912 NAMED_OBJECT_CONST);
4913 Named_constant* named_constant = new Named_constant(tid.type(), expr,
4914 iota_value,
4915 tid.location());
4916 named_object->u_.const_value = named_constant;
4917 return named_object;
4920 // Make a named type.
4922 Named_object*
4923 Named_object::make_type(const std::string& name, const Package* package,
4924 Type* type, Location location)
4926 Named_object* named_object = new Named_object(name, package,
4927 NAMED_OBJECT_TYPE);
4928 Named_type* named_type = Type::make_named_type(named_object, type, location);
4929 named_object->u_.type_value = named_type;
4930 return named_object;
4933 // Make a type declaration.
4935 Named_object*
4936 Named_object::make_type_declaration(const std::string& name,
4937 const Package* package,
4938 Location location)
4940 Named_object* named_object = new Named_object(name, package,
4941 NAMED_OBJECT_TYPE_DECLARATION);
4942 Type_declaration* type_declaration = new Type_declaration(location);
4943 named_object->u_.type_declaration = type_declaration;
4944 return named_object;
4947 // Make a variable.
4949 Named_object*
4950 Named_object::make_variable(const std::string& name, const Package* package,
4951 Variable* variable)
4953 Named_object* named_object = new Named_object(name, package,
4954 NAMED_OBJECT_VAR);
4955 named_object->u_.var_value = variable;
4956 return named_object;
4959 // Make a result variable.
4961 Named_object*
4962 Named_object::make_result_variable(const std::string& name,
4963 Result_variable* result)
4965 Named_object* named_object = new Named_object(name, NULL,
4966 NAMED_OBJECT_RESULT_VAR);
4967 named_object->u_.result_var_value = result;
4968 return named_object;
4971 // Make a sink. This is used for the special blank identifier _.
4973 Named_object*
4974 Named_object::make_sink()
4976 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4979 // Make a named function.
4981 Named_object*
4982 Named_object::make_function(const std::string& name, const Package* package,
4983 Function* function)
4985 Named_object* named_object = new Named_object(name, package,
4986 NAMED_OBJECT_FUNC);
4987 named_object->u_.func_value = function;
4988 return named_object;
4991 // Make a function declaration.
4993 Named_object*
4994 Named_object::make_function_declaration(const std::string& name,
4995 const Package* package,
4996 Function_type* fntype,
4997 Location location)
4999 Named_object* named_object = new Named_object(name, package,
5000 NAMED_OBJECT_FUNC_DECLARATION);
5001 Function_declaration *func_decl = new Function_declaration(fntype, location);
5002 named_object->u_.func_declaration_value = func_decl;
5003 return named_object;
5006 // Make a package.
5008 Named_object*
5009 Named_object::make_package(const std::string& alias, Package* package)
5011 Named_object* named_object = new Named_object(alias, NULL,
5012 NAMED_OBJECT_PACKAGE);
5013 named_object->u_.package_value = package;
5014 return named_object;
5017 // Return the name to use in an error message.
5019 std::string
5020 Named_object::message_name() const
5022 if (this->package_ == NULL)
5023 return Gogo::message_name(this->name_);
5024 std::string ret;
5025 if (this->package_->has_package_name())
5026 ret = this->package_->package_name();
5027 else
5028 ret = this->package_->pkgpath();
5029 ret = Gogo::message_name(ret);
5030 ret += '.';
5031 ret += Gogo::message_name(this->name_);
5032 return ret;
5035 // Set the type when a declaration is defined.
5037 void
5038 Named_object::set_type_value(Named_type* named_type)
5040 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
5041 Type_declaration* td = this->u_.type_declaration;
5042 td->define_methods(named_type);
5043 unsigned int index;
5044 Named_object* in_function = td->in_function(&index);
5045 if (in_function != NULL)
5046 named_type->set_in_function(in_function, index);
5047 delete td;
5048 this->classification_ = NAMED_OBJECT_TYPE;
5049 this->u_.type_value = named_type;
5052 // Define a function which was previously declared.
5054 void
5055 Named_object::set_function_value(Function* function)
5057 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
5058 if (this->func_declaration_value()->has_descriptor())
5060 Expression* descriptor =
5061 this->func_declaration_value()->descriptor(NULL, NULL);
5062 function->set_descriptor(descriptor);
5064 this->classification_ = NAMED_OBJECT_FUNC;
5065 // FIXME: We should free the old value.
5066 this->u_.func_value = function;
5069 // Declare an unknown object as a type declaration.
5071 void
5072 Named_object::declare_as_type()
5074 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
5075 Unknown_name* unk = this->u_.unknown_value;
5076 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
5077 this->u_.type_declaration = new Type_declaration(unk->location());
5078 delete unk;
5081 // Return the location of a named object.
5083 Location
5084 Named_object::location() const
5086 switch (this->classification_)
5088 default:
5089 case NAMED_OBJECT_UNINITIALIZED:
5090 go_unreachable();
5092 case NAMED_OBJECT_ERRONEOUS:
5093 return Linemap::unknown_location();
5095 case NAMED_OBJECT_UNKNOWN:
5096 return this->unknown_value()->location();
5098 case NAMED_OBJECT_CONST:
5099 return this->const_value()->location();
5101 case NAMED_OBJECT_TYPE:
5102 return this->type_value()->location();
5104 case NAMED_OBJECT_TYPE_DECLARATION:
5105 return this->type_declaration_value()->location();
5107 case NAMED_OBJECT_VAR:
5108 return this->var_value()->location();
5110 case NAMED_OBJECT_RESULT_VAR:
5111 return this->result_var_value()->location();
5113 case NAMED_OBJECT_SINK:
5114 go_unreachable();
5116 case NAMED_OBJECT_FUNC:
5117 return this->func_value()->location();
5119 case NAMED_OBJECT_FUNC_DECLARATION:
5120 return this->func_declaration_value()->location();
5122 case NAMED_OBJECT_PACKAGE:
5123 return this->package_value()->location();
5127 // Export a named object.
5129 void
5130 Named_object::export_named_object(Export* exp) const
5132 switch (this->classification_)
5134 default:
5135 case NAMED_OBJECT_UNINITIALIZED:
5136 case NAMED_OBJECT_UNKNOWN:
5137 go_unreachable();
5139 case NAMED_OBJECT_ERRONEOUS:
5140 break;
5142 case NAMED_OBJECT_CONST:
5143 this->const_value()->export_const(exp, this->name_);
5144 break;
5146 case NAMED_OBJECT_TYPE:
5147 this->type_value()->export_named_type(exp, this->name_);
5148 break;
5150 case NAMED_OBJECT_TYPE_DECLARATION:
5151 error_at(this->type_declaration_value()->location(),
5152 "attempt to export %<%s%> which was declared but not defined",
5153 this->message_name().c_str());
5154 break;
5156 case NAMED_OBJECT_FUNC_DECLARATION:
5157 this->func_declaration_value()->export_func(exp, this->name_);
5158 break;
5160 case NAMED_OBJECT_VAR:
5161 this->var_value()->export_var(exp, this->name_);
5162 break;
5164 case NAMED_OBJECT_RESULT_VAR:
5165 case NAMED_OBJECT_SINK:
5166 go_unreachable();
5168 case NAMED_OBJECT_FUNC:
5169 this->func_value()->export_func(exp, this->name_);
5170 break;
5174 // Convert a variable to the backend representation.
5176 Bvariable*
5177 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
5179 if (this->classification_ == NAMED_OBJECT_VAR)
5180 return this->var_value()->get_backend_variable(gogo, function,
5181 this->package_, this->name_);
5182 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
5183 return this->result_var_value()->get_backend_variable(gogo, function,
5184 this->name_);
5185 else
5186 go_unreachable();
5190 // Return the external identifier for this object.
5192 std::string
5193 Named_object::get_id(Gogo* gogo)
5195 go_assert(!this->is_variable() && !this->is_result_variable());
5196 std::string decl_name;
5197 if (this->is_function_declaration()
5198 && !this->func_declaration_value()->asm_name().empty())
5199 decl_name = this->func_declaration_value()->asm_name();
5200 else if (this->is_type()
5201 && Linemap::is_predeclared_location(this->type_value()->location()))
5203 // We don't need the package name for builtin types.
5204 decl_name = Gogo::unpack_hidden_name(this->name_);
5206 else
5208 std::string package_name;
5209 if (this->package_ == NULL)
5210 package_name = gogo->package_name();
5211 else
5212 package_name = this->package_->package_name();
5214 // Note that this will be misleading if this is an unexported
5215 // method generated for an embedded imported type. In that case
5216 // the unexported method should have the package name of the
5217 // package from which it is imported, but we are going to give
5218 // it our package name. Fixing this would require knowing the
5219 // package name, but we only know the package path. It might be
5220 // better to use package paths here anyhow. This doesn't affect
5221 // the assembler code, because we always set that name in
5222 // Function::get_or_make_decl anyhow. FIXME.
5224 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
5226 Function_type* fntype;
5227 if (this->is_function())
5228 fntype = this->func_value()->type();
5229 else if (this->is_function_declaration())
5230 fntype = this->func_declaration_value()->type();
5231 else
5232 fntype = NULL;
5233 if (fntype != NULL && fntype->is_method())
5235 decl_name.push_back('.');
5236 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
5239 if (this->is_type())
5241 unsigned int index;
5242 const Named_object* in_function = this->type_value()->in_function(&index);
5243 if (in_function != NULL)
5245 decl_name += '$' + Gogo::unpack_hidden_name(in_function->name());
5246 if (index > 0)
5248 char buf[30];
5249 snprintf(buf, sizeof buf, "%u", index);
5250 decl_name += '$';
5251 decl_name += buf;
5255 return decl_name;
5258 // Class Bindings.
5260 Bindings::Bindings(Bindings* enclosing)
5261 : enclosing_(enclosing), named_objects_(), bindings_()
5265 // Clear imports.
5267 void
5268 Bindings::clear_file_scope(Gogo* gogo)
5270 Contour::iterator p = this->bindings_.begin();
5271 while (p != this->bindings_.end())
5273 bool keep;
5274 if (p->second->package() != NULL)
5275 keep = false;
5276 else if (p->second->is_package())
5277 keep = false;
5278 else if (p->second->is_function()
5279 && !p->second->func_value()->type()->is_method()
5280 && Gogo::unpack_hidden_name(p->second->name()) == "init")
5281 keep = false;
5282 else
5283 keep = true;
5285 if (keep)
5286 ++p;
5287 else
5289 gogo->add_file_block_name(p->second->name(), p->second->location());
5290 p = this->bindings_.erase(p);
5295 // Look up a symbol.
5297 Named_object*
5298 Bindings::lookup(const std::string& name) const
5300 Contour::const_iterator p = this->bindings_.find(name);
5301 if (p != this->bindings_.end())
5302 return p->second->resolve();
5303 else if (this->enclosing_ != NULL)
5304 return this->enclosing_->lookup(name);
5305 else
5306 return NULL;
5309 // Look up a symbol locally.
5311 Named_object*
5312 Bindings::lookup_local(const std::string& name) const
5314 Contour::const_iterator p = this->bindings_.find(name);
5315 if (p == this->bindings_.end())
5316 return NULL;
5317 return p->second;
5320 // Remove an object from a set of bindings. This is used for a
5321 // special case in thunks for functions which call recover.
5323 void
5324 Bindings::remove_binding(Named_object* no)
5326 Contour::iterator pb = this->bindings_.find(no->name());
5327 go_assert(pb != this->bindings_.end());
5328 this->bindings_.erase(pb);
5329 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
5330 pn != this->named_objects_.end();
5331 ++pn)
5333 if (*pn == no)
5335 this->named_objects_.erase(pn);
5336 return;
5339 go_unreachable();
5342 // Add a method to the list of objects. This is not added to the
5343 // lookup table. This is so that we have a single list of objects
5344 // declared at the top level, which we walk through when it's time to
5345 // convert to trees.
5347 void
5348 Bindings::add_method(Named_object* method)
5350 this->named_objects_.push_back(method);
5353 // Add a generic Named_object to a Contour.
5355 Named_object*
5356 Bindings::add_named_object_to_contour(Contour* contour,
5357 Named_object* named_object)
5359 go_assert(named_object == named_object->resolve());
5360 const std::string& name(named_object->name());
5361 go_assert(!Gogo::is_sink_name(name));
5363 std::pair<Contour::iterator, bool> ins =
5364 contour->insert(std::make_pair(name, named_object));
5365 if (!ins.second)
5367 // The name was already there.
5368 if (named_object->package() != NULL
5369 && ins.first->second->package() == named_object->package()
5370 && (ins.first->second->classification()
5371 == named_object->classification()))
5373 // This is a second import of the same object.
5374 return ins.first->second;
5376 ins.first->second = this->new_definition(ins.first->second,
5377 named_object);
5378 return ins.first->second;
5380 else
5382 // Don't push declarations on the list. We push them on when
5383 // and if we find the definitions. That way we genericize the
5384 // functions in order.
5385 if (!named_object->is_type_declaration()
5386 && !named_object->is_function_declaration()
5387 && !named_object->is_unknown())
5388 this->named_objects_.push_back(named_object);
5389 return named_object;
5393 // We had an existing named object OLD_OBJECT, and we've seen a new
5394 // one NEW_OBJECT with the same name. FIXME: This does not free the
5395 // new object when we don't need it.
5397 Named_object*
5398 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
5400 if (new_object->is_erroneous() && !old_object->is_erroneous())
5401 return new_object;
5403 std::string reason;
5404 switch (old_object->classification())
5406 default:
5407 case Named_object::NAMED_OBJECT_UNINITIALIZED:
5408 go_unreachable();
5410 case Named_object::NAMED_OBJECT_ERRONEOUS:
5411 return old_object;
5413 case Named_object::NAMED_OBJECT_UNKNOWN:
5415 Named_object* real = old_object->unknown_value()->real_named_object();
5416 if (real != NULL)
5417 return this->new_definition(real, new_object);
5418 go_assert(!new_object->is_unknown());
5419 old_object->unknown_value()->set_real_named_object(new_object);
5420 if (!new_object->is_type_declaration()
5421 && !new_object->is_function_declaration())
5422 this->named_objects_.push_back(new_object);
5423 return new_object;
5426 case Named_object::NAMED_OBJECT_CONST:
5427 break;
5429 case Named_object::NAMED_OBJECT_TYPE:
5430 if (new_object->is_type_declaration())
5431 return old_object;
5432 break;
5434 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5435 if (new_object->is_type_declaration())
5436 return old_object;
5437 if (new_object->is_type())
5439 old_object->set_type_value(new_object->type_value());
5440 new_object->type_value()->set_named_object(old_object);
5441 this->named_objects_.push_back(old_object);
5442 return old_object;
5444 break;
5446 case Named_object::NAMED_OBJECT_VAR:
5447 case Named_object::NAMED_OBJECT_RESULT_VAR:
5448 // We have already given an error in the parser for cases where
5449 // one parameter or result variable redeclares another one.
5450 if ((new_object->is_variable()
5451 && new_object->var_value()->is_parameter())
5452 || new_object->is_result_variable())
5453 return old_object;
5454 break;
5456 case Named_object::NAMED_OBJECT_SINK:
5457 go_unreachable();
5459 case Named_object::NAMED_OBJECT_FUNC:
5460 if (new_object->is_function_declaration())
5462 if (!new_object->func_declaration_value()->asm_name().empty())
5463 sorry("__asm__ for function definitions");
5464 Function_type* old_type = old_object->func_value()->type();
5465 Function_type* new_type =
5466 new_object->func_declaration_value()->type();
5467 if (old_type->is_valid_redeclaration(new_type, &reason))
5468 return old_object;
5470 break;
5472 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5474 Function_type* old_type = old_object->func_declaration_value()->type();
5475 if (new_object->is_function_declaration())
5477 Function_type* new_type =
5478 new_object->func_declaration_value()->type();
5479 if (old_type->is_valid_redeclaration(new_type, &reason))
5480 return old_object;
5482 if (new_object->is_function())
5484 Function_type* new_type = new_object->func_value()->type();
5485 if (old_type->is_valid_redeclaration(new_type, &reason))
5487 if (!old_object->func_declaration_value()->asm_name().empty())
5488 sorry("__asm__ for function definitions");
5489 old_object->set_function_value(new_object->func_value());
5490 this->named_objects_.push_back(old_object);
5491 return old_object;
5495 break;
5497 case Named_object::NAMED_OBJECT_PACKAGE:
5498 break;
5501 std::string n = old_object->message_name();
5502 if (reason.empty())
5503 error_at(new_object->location(), "redefinition of %qs", n.c_str());
5504 else
5505 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
5506 reason.c_str());
5508 inform(old_object->location(), "previous definition of %qs was here",
5509 n.c_str());
5511 return old_object;
5514 // Add a named type.
5516 Named_object*
5517 Bindings::add_named_type(Named_type* named_type)
5519 return this->add_named_object(named_type->named_object());
5522 // Add a function.
5524 Named_object*
5525 Bindings::add_function(const std::string& name, const Package* package,
5526 Function* function)
5528 return this->add_named_object(Named_object::make_function(name, package,
5529 function));
5532 // Add a function declaration.
5534 Named_object*
5535 Bindings::add_function_declaration(const std::string& name,
5536 const Package* package,
5537 Function_type* type,
5538 Location location)
5540 Named_object* no = Named_object::make_function_declaration(name, package,
5541 type, location);
5542 return this->add_named_object(no);
5545 // Define a type which was previously declared.
5547 void
5548 Bindings::define_type(Named_object* no, Named_type* type)
5550 no->set_type_value(type);
5551 this->named_objects_.push_back(no);
5554 // Mark all local variables as used. This is used for some types of
5555 // parse error.
5557 void
5558 Bindings::mark_locals_used()
5560 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
5561 p != this->named_objects_.end();
5562 ++p)
5563 if ((*p)->is_variable())
5564 (*p)->var_value()->set_is_used();
5567 // Traverse bindings.
5570 Bindings::traverse(Traverse* traverse, bool is_global)
5572 unsigned int traverse_mask = traverse->traverse_mask();
5574 // We don't use an iterator because we permit the traversal to add
5575 // new global objects.
5576 const unsigned int e_or_t = (Traverse::traverse_expressions
5577 | Traverse::traverse_types);
5578 const unsigned int e_or_t_or_s = (e_or_t
5579 | Traverse::traverse_statements);
5580 for (size_t i = 0; i < this->named_objects_.size(); ++i)
5582 Named_object* p = this->named_objects_[i];
5583 int t = TRAVERSE_CONTINUE;
5584 switch (p->classification())
5586 case Named_object::NAMED_OBJECT_CONST:
5587 if ((traverse_mask & Traverse::traverse_constants) != 0)
5588 t = traverse->constant(p, is_global);
5589 if (t == TRAVERSE_CONTINUE
5590 && (traverse_mask & e_or_t) != 0)
5592 Type* tc = p->const_value()->type();
5593 if (tc != NULL
5594 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5595 return TRAVERSE_EXIT;
5596 t = p->const_value()->traverse_expression(traverse);
5598 break;
5600 case Named_object::NAMED_OBJECT_VAR:
5601 case Named_object::NAMED_OBJECT_RESULT_VAR:
5602 if ((traverse_mask & Traverse::traverse_variables) != 0)
5603 t = traverse->variable(p);
5604 if (t == TRAVERSE_CONTINUE
5605 && (traverse_mask & e_or_t) != 0)
5607 if (p->is_result_variable()
5608 || p->var_value()->has_type())
5610 Type* tv = (p->is_variable()
5611 ? p->var_value()->type()
5612 : p->result_var_value()->type());
5613 if (tv != NULL
5614 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5615 return TRAVERSE_EXIT;
5618 if (t == TRAVERSE_CONTINUE
5619 && (traverse_mask & e_or_t_or_s) != 0
5620 && p->is_variable())
5621 t = p->var_value()->traverse_expression(traverse, traverse_mask);
5622 break;
5624 case Named_object::NAMED_OBJECT_FUNC:
5625 if ((traverse_mask & Traverse::traverse_functions) != 0)
5626 t = traverse->function(p);
5628 if (t == TRAVERSE_CONTINUE
5629 && (traverse_mask
5630 & (Traverse::traverse_variables
5631 | Traverse::traverse_constants
5632 | Traverse::traverse_functions
5633 | Traverse::traverse_blocks
5634 | Traverse::traverse_statements
5635 | Traverse::traverse_expressions
5636 | Traverse::traverse_types)) != 0)
5637 t = p->func_value()->traverse(traverse);
5638 break;
5640 case Named_object::NAMED_OBJECT_PACKAGE:
5641 // These are traversed in Gogo::traverse.
5642 go_assert(is_global);
5643 break;
5645 case Named_object::NAMED_OBJECT_TYPE:
5646 if ((traverse_mask & e_or_t) != 0)
5647 t = Type::traverse(p->type_value(), traverse);
5648 break;
5650 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5651 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5652 case Named_object::NAMED_OBJECT_UNKNOWN:
5653 case Named_object::NAMED_OBJECT_ERRONEOUS:
5654 break;
5656 case Named_object::NAMED_OBJECT_SINK:
5657 default:
5658 go_unreachable();
5661 if (t == TRAVERSE_EXIT)
5662 return TRAVERSE_EXIT;
5665 // If we need to traverse types, check the function declarations,
5666 // which have types. Also check any methods of a type declaration.
5667 if ((traverse_mask & e_or_t) != 0)
5669 for (Bindings::const_declarations_iterator p =
5670 this->begin_declarations();
5671 p != this->end_declarations();
5672 ++p)
5674 if (p->second->is_function_declaration())
5676 if (Type::traverse(p->second->func_declaration_value()->type(),
5677 traverse)
5678 == TRAVERSE_EXIT)
5679 return TRAVERSE_EXIT;
5681 else if (p->second->is_type_declaration())
5683 const std::vector<Named_object*>* methods =
5684 p->second->type_declaration_value()->methods();
5685 for (std::vector<Named_object*>::const_iterator pm =
5686 methods->begin();
5687 pm != methods->end();
5688 pm++)
5690 Named_object* no = *pm;
5691 Type *t;
5692 if (no->is_function())
5693 t = no->func_value()->type();
5694 else if (no->is_function_declaration())
5695 t = no->func_declaration_value()->type();
5696 else
5697 continue;
5698 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
5699 return TRAVERSE_EXIT;
5705 return TRAVERSE_CONTINUE;
5708 // Class Label.
5710 // Clear any references to this label.
5712 void
5713 Label::clear_refs()
5715 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
5716 p != this->refs_.end();
5717 ++p)
5718 delete *p;
5719 this->refs_.clear();
5722 // Get the backend representation for a label.
5724 Blabel*
5725 Label::get_backend_label(Translate_context* context)
5727 if (this->blabel_ == NULL)
5729 Function* function = context->function()->func_value();
5730 tree fndecl = function->get_decl();
5731 Bfunction* bfunction = tree_to_function(fndecl);
5732 this->blabel_ = context->backend()->label(bfunction, this->name_,
5733 this->location_);
5735 return this->blabel_;
5738 // Return an expression for the address of this label.
5740 Bexpression*
5741 Label::get_addr(Translate_context* context, Location location)
5743 Blabel* label = this->get_backend_label(context);
5744 return context->backend()->label_address(label, location);
5747 // Class Unnamed_label.
5749 // Get the backend representation for an unnamed label.
5751 Blabel*
5752 Unnamed_label::get_blabel(Translate_context* context)
5754 if (this->blabel_ == NULL)
5756 Function* function = context->function()->func_value();
5757 tree fndecl = function->get_decl();
5758 Bfunction* bfunction = tree_to_function(fndecl);
5759 this->blabel_ = context->backend()->label(bfunction, "",
5760 this->location_);
5762 return this->blabel_;
5765 // Return a statement which defines this unnamed label.
5767 Bstatement*
5768 Unnamed_label::get_definition(Translate_context* context)
5770 Blabel* blabel = this->get_blabel(context);
5771 return context->backend()->label_definition_statement(blabel);
5774 // Return a goto statement to this unnamed label.
5776 Bstatement*
5777 Unnamed_label::get_goto(Translate_context* context, Location location)
5779 Blabel* blabel = this->get_blabel(context);
5780 return context->backend()->goto_statement(blabel, location);
5783 // Class Package.
5785 Package::Package(const std::string& pkgpath, Location location)
5786 : pkgpath_(pkgpath), pkgpath_symbol_(Gogo::pkgpath_for_symbol(pkgpath)),
5787 package_name_(), bindings_(new Bindings(NULL)), priority_(0),
5788 location_(location), used_(false), is_imported_(false),
5789 uses_sink_alias_(false)
5791 go_assert(!pkgpath.empty());
5795 // Set the package name.
5797 void
5798 Package::set_package_name(const std::string& package_name, Location location)
5800 go_assert(!package_name.empty());
5801 if (this->package_name_.empty())
5802 this->package_name_ = package_name;
5803 else if (this->package_name_ != package_name)
5804 error_at(location,
5805 "saw two different packages with the same package path %s: %s, %s",
5806 this->pkgpath_.c_str(), this->package_name_.c_str(),
5807 package_name.c_str());
5810 // Set the priority. We may see multiple priorities for an imported
5811 // package; we want to use the largest one.
5813 void
5814 Package::set_priority(int priority)
5816 if (priority > this->priority_)
5817 this->priority_ = priority;
5820 // Determine types of constants. Everything else in a package
5821 // (variables, function declarations) should already have a fixed
5822 // type. Constants may have abstract types.
5824 void
5825 Package::determine_types()
5827 Bindings* bindings = this->bindings_;
5828 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5829 p != bindings->end_definitions();
5830 ++p)
5832 if ((*p)->is_const())
5833 (*p)->const_value()->determine_type();
5837 // Class Traverse.
5839 // Destructor.
5841 Traverse::~Traverse()
5843 if (this->types_seen_ != NULL)
5844 delete this->types_seen_;
5845 if (this->expressions_seen_ != NULL)
5846 delete this->expressions_seen_;
5849 // Record that we are looking at a type, and return true if we have
5850 // already seen it.
5852 bool
5853 Traverse::remember_type(const Type* type)
5855 if (type->is_error_type())
5856 return true;
5857 go_assert((this->traverse_mask() & traverse_types) != 0
5858 || (this->traverse_mask() & traverse_expressions) != 0);
5859 // We mostly only have to remember named types. But it turns out
5860 // that an interface type can refer to itself without using a name
5861 // by relying on interface inheritance, as in
5862 // type I interface { F() interface{I} }
5863 if (type->classification() != Type::TYPE_NAMED
5864 && type->classification() != Type::TYPE_INTERFACE)
5865 return false;
5866 if (this->types_seen_ == NULL)
5867 this->types_seen_ = new Types_seen();
5868 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
5869 return !ins.second;
5872 // Record that we are looking at an expression, and return true if we
5873 // have already seen it.
5875 bool
5876 Traverse::remember_expression(const Expression* expression)
5878 go_assert((this->traverse_mask() & traverse_types) != 0
5879 || (this->traverse_mask() & traverse_expressions) != 0);
5880 if (this->expressions_seen_ == NULL)
5881 this->expressions_seen_ = new Expressions_seen();
5882 std::pair<Expressions_seen::iterator, bool> ins =
5883 this->expressions_seen_->insert(expression);
5884 return !ins.second;
5887 // The default versions of these functions should never be called: the
5888 // traversal mask indicates which functions may be called.
5891 Traverse::variable(Named_object*)
5893 go_unreachable();
5897 Traverse::constant(Named_object*, bool)
5899 go_unreachable();
5903 Traverse::function(Named_object*)
5905 go_unreachable();
5909 Traverse::block(Block*)
5911 go_unreachable();
5915 Traverse::statement(Block*, size_t*, Statement*)
5917 go_unreachable();
5921 Traverse::expression(Expression**)
5923 go_unreachable();
5927 Traverse::type(Type*)
5929 go_unreachable();
5932 // Class Statement_inserter.
5934 void
5935 Statement_inserter::insert(Statement* s)
5937 if (this->block_ != NULL)
5939 go_assert(this->pindex_ != NULL);
5940 this->block_->insert_statement_before(*this->pindex_, s);
5941 ++*this->pindex_;
5943 else if (this->var_ != NULL)
5944 this->var_->add_preinit_statement(this->gogo_, s);
5945 else
5946 go_assert(saw_errors());