compiler: revert `for package-scope "a = b; b = x" just set "a = x"`
[official-gcc.git] / gcc / go / gofrontend / gogo.cc
blobd35c6baf5825f8a1fd4a01e894837a7a089a3091
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 <fstream>
11 #include "filenames.h"
13 #include "go-c.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
16 #include "go-dump.h"
17 #include "go-optimize.h"
18 #include "lex.h"
19 #include "types.h"
20 #include "statements.h"
21 #include "expressions.h"
22 #include "runtime.h"
23 #include "import.h"
24 #include "export.h"
25 #include "backend.h"
26 #include "gogo.h"
28 // Class Gogo.
30 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
31 : backend_(backend),
32 linemap_(linemap),
33 package_(NULL),
34 functions_(),
35 globals_(new Bindings(NULL)),
36 file_block_names_(),
37 imports_(),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
40 current_file_imported_embed_(false),
41 packages_(),
42 init_functions_(),
43 var_deps_(),
44 need_init_fn_(false),
45 init_fn_name_(),
46 imported_init_fns_(),
47 pkgpath_(),
48 pkgpath_symbol_(),
49 prefix_(),
50 pkgpath_set_(false),
51 pkgpath_from_option_(false),
52 prefix_from_option_(false),
53 relative_import_path_(),
54 c_header_(),
55 check_divide_by_zero_(true),
56 check_divide_overflow_(true),
57 compiling_runtime_(false),
58 debug_escape_level_(0),
59 debug_optimization_(false),
60 nil_check_size_threshold_(4096),
61 need_eqtype_(false),
62 verify_types_(),
63 interface_types_(),
64 specific_type_functions_(),
65 specific_type_functions_are_written_(false),
66 named_types_are_converted_(false),
67 analysis_sets_(),
68 gc_roots_(),
69 type_descriptors_(),
70 imported_inlinable_functions_(),
71 imported_inline_functions_()
73 const Location loc = Linemap::predeclared_location();
75 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
76 RUNTIME_TYPE_KIND_UINT8);
77 this->add_named_type(uint8_type);
78 this->add_named_type(Type::make_integer_type("uint16", true, 16,
79 RUNTIME_TYPE_KIND_UINT16));
80 this->add_named_type(Type::make_integer_type("uint32", true, 32,
81 RUNTIME_TYPE_KIND_UINT32));
82 this->add_named_type(Type::make_integer_type("uint64", true, 64,
83 RUNTIME_TYPE_KIND_UINT64));
85 this->add_named_type(Type::make_integer_type("int8", false, 8,
86 RUNTIME_TYPE_KIND_INT8));
87 this->add_named_type(Type::make_integer_type("int16", false, 16,
88 RUNTIME_TYPE_KIND_INT16));
89 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
90 RUNTIME_TYPE_KIND_INT32);
91 this->add_named_type(int32_type);
92 this->add_named_type(Type::make_integer_type("int64", false, 64,
93 RUNTIME_TYPE_KIND_INT64));
95 this->add_named_type(Type::make_float_type("float32", 32,
96 RUNTIME_TYPE_KIND_FLOAT32));
97 this->add_named_type(Type::make_float_type("float64", 64,
98 RUNTIME_TYPE_KIND_FLOAT64));
100 this->add_named_type(Type::make_complex_type("complex64", 64,
101 RUNTIME_TYPE_KIND_COMPLEX64));
102 this->add_named_type(Type::make_complex_type("complex128", 128,
103 RUNTIME_TYPE_KIND_COMPLEX128));
105 int int_type_size = pointer_size;
106 if (int_type_size < 32)
107 int_type_size = 32;
108 this->add_named_type(Type::make_integer_type("uint", true,
109 int_type_size,
110 RUNTIME_TYPE_KIND_UINT));
111 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
112 RUNTIME_TYPE_KIND_INT);
113 this->add_named_type(int_type);
115 this->add_named_type(Type::make_integer_type("uintptr", true,
116 pointer_size,
117 RUNTIME_TYPE_KIND_UINTPTR));
119 // "byte" is an alias for "uint8".
120 uint8_type->integer_type()->set_is_byte();
121 this->add_named_type(Type::make_integer_type_alias("byte", uint8_type));
123 // "rune" is an alias for "int32".
124 int32_type->integer_type()->set_is_rune();
125 this->add_named_type(Type::make_integer_type_alias("rune", int32_type));
127 this->add_named_type(Type::make_named_bool_type());
129 this->add_named_type(Type::make_named_string_type());
131 // "error" is interface { Error() string }.
133 Typed_identifier_list *methods = new Typed_identifier_list;
134 Typed_identifier_list *results = new Typed_identifier_list;
135 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
136 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
137 methods->push_back(Typed_identifier("Error", method_type, loc));
138 Interface_type *error_iface = Type::make_interface_type(methods, loc);
139 error_iface->finalize_methods();
140 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
141 this->add_named_type(error_type);
144 // "any" is an alias for the empty interface type.
146 Type* empty = Type::make_empty_interface_type(loc);
147 Named_object* no = Named_object::make_type("any", NULL, empty, loc);
148 Named_type* nt = no->type_value();
149 nt->set_is_alias();
150 this->add_named_type(nt);
153 this->globals_->add_constant(Typed_identifier("true",
154 Type::make_boolean_type(),
155 loc),
156 NULL,
157 Expression::make_boolean(true, loc),
159 this->globals_->add_constant(Typed_identifier("false",
160 Type::make_boolean_type(),
161 loc),
162 NULL,
163 Expression::make_boolean(false, loc),
166 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
167 loc),
168 NULL,
169 Expression::make_nil(loc),
172 Type* abstract_int_type = Type::make_abstract_integer_type();
173 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
174 loc),
175 NULL,
176 Expression::make_iota(),
179 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
180 new_type->set_is_varargs();
181 new_type->set_is_builtin();
182 this->globals_->add_function_declaration("new", NULL, new_type, loc);
184 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
185 make_type->set_is_varargs();
186 make_type->set_is_builtin();
187 this->globals_->add_function_declaration("make", NULL, make_type, loc);
189 Typed_identifier_list* len_result = new Typed_identifier_list();
190 len_result->push_back(Typed_identifier("", int_type, loc));
191 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
192 loc);
193 len_type->set_is_builtin();
194 this->globals_->add_function_declaration("len", NULL, len_type, loc);
196 Typed_identifier_list* cap_result = new Typed_identifier_list();
197 cap_result->push_back(Typed_identifier("", int_type, loc));
198 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
199 loc);
200 cap_type->set_is_builtin();
201 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
203 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
204 print_type->set_is_varargs();
205 print_type->set_is_builtin();
206 this->globals_->add_function_declaration("print", NULL, print_type, loc);
208 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
209 print_type->set_is_varargs();
210 print_type->set_is_builtin();
211 this->globals_->add_function_declaration("println", NULL, print_type, loc);
213 Type *empty = Type::make_empty_interface_type(loc);
214 Typed_identifier_list* panic_parms = new Typed_identifier_list();
215 panic_parms->push_back(Typed_identifier("e", empty, loc));
216 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
217 NULL, loc);
218 panic_type->set_is_builtin();
219 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
221 Typed_identifier_list* recover_result = new Typed_identifier_list();
222 recover_result->push_back(Typed_identifier("", empty, loc));
223 Function_type* recover_type = Type::make_function_type(NULL, NULL,
224 recover_result,
225 loc);
226 recover_type->set_is_builtin();
227 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
229 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
230 close_type->set_is_varargs();
231 close_type->set_is_builtin();
232 this->globals_->add_function_declaration("close", NULL, close_type, loc);
234 Typed_identifier_list* copy_result = new Typed_identifier_list();
235 copy_result->push_back(Typed_identifier("", int_type, loc));
236 Function_type* copy_type = Type::make_function_type(NULL, NULL,
237 copy_result, loc);
238 copy_type->set_is_varargs();
239 copy_type->set_is_builtin();
240 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
242 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
243 append_type->set_is_varargs();
244 append_type->set_is_builtin();
245 this->globals_->add_function_declaration("append", NULL, append_type, loc);
247 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
248 complex_type->set_is_varargs();
249 complex_type->set_is_builtin();
250 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
252 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
253 real_type->set_is_varargs();
254 real_type->set_is_builtin();
255 this->globals_->add_function_declaration("real", NULL, real_type, loc);
257 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
258 imag_type->set_is_varargs();
259 imag_type->set_is_builtin();
260 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
262 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
263 delete_type->set_is_varargs();
264 delete_type->set_is_builtin();
265 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
268 std::string
269 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
271 go_assert(!pkgpath.empty());
272 return go_encode_id(pkgpath);
275 // Return a hash code for a string, given a starting hash.
277 unsigned int
278 Gogo::hash_string(const std::string& s, unsigned int h)
280 const char* p = s.data();
281 size_t len = s.length();
282 for (; len > 0; --len)
284 h ^= *p++;
285 h*= 16777619;
287 return h;
290 // Get the package path to use for type reflection data. This should
291 // ideally be unique across the entire link.
293 const std::string&
294 Gogo::pkgpath() const
296 go_assert(this->pkgpath_set_);
297 return this->pkgpath_;
300 // Set the package path from the -fgo-pkgpath command line option.
302 void
303 Gogo::set_pkgpath(const std::string& arg)
305 go_assert(!this->pkgpath_set_);
306 this->pkgpath_ = arg;
307 this->pkgpath_set_ = true;
308 this->pkgpath_from_option_ = true;
311 // Get the package path to use for symbol names.
313 const std::string&
314 Gogo::pkgpath_symbol() const
316 go_assert(this->pkgpath_set_);
317 return this->pkgpath_symbol_;
320 // Set the unique prefix to use to determine the package path, from
321 // the -fgo-prefix command line option.
323 void
324 Gogo::set_prefix(const std::string& arg)
326 go_assert(!this->prefix_from_option_);
327 this->prefix_ = arg;
328 this->prefix_from_option_ = true;
331 // Munge name for use in an error message.
333 std::string
334 Gogo::message_name(const std::string& name)
336 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
339 // Get the package name.
341 const std::string&
342 Gogo::package_name() const
344 go_assert(this->package_ != NULL);
345 return this->package_->package_name();
348 // Set the package name.
350 void
351 Gogo::set_package_name(const std::string& package_name,
352 Location location)
354 if (this->package_ != NULL)
356 if (this->package_->package_name() != package_name)
357 go_error_at(location, "expected package %<%s%>",
358 Gogo::message_name(this->package_->package_name()).c_str());
359 return;
362 // Now that we know the name of the package we are compiling, set
363 // the package path to use for reflect.Type.PkgPath and global
364 // symbol names.
365 if (this->pkgpath_set_)
366 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
367 else
369 if (!this->prefix_from_option_ && package_name == "main")
371 this->pkgpath_ = package_name;
372 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name);
374 else
376 if (!this->prefix_from_option_)
377 this->prefix_ = "go";
378 this->pkgpath_ = this->prefix_ + '.' + package_name;
379 this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.'
380 + Gogo::pkgpath_for_symbol(package_name));
382 this->pkgpath_set_ = true;
385 this->package_ = this->register_package(this->pkgpath_,
386 this->pkgpath_symbol_, location);
387 this->package_->set_package_name(package_name, location);
389 if (this->is_main_package())
391 // Declare "main" as a function which takes no parameters and
392 // returns no value.
393 Location uloc = Linemap::unknown_location();
394 this->declare_function(Gogo::pack_hidden_name("main", false),
395 Type::make_function_type (NULL, NULL, NULL, uloc),
396 uloc);
400 // Return whether this is the "main" package. This is not true if
401 // -fgo-pkgpath or -fgo-prefix was used.
403 bool
404 Gogo::is_main_package() const
406 return (this->package_name() == "main"
407 && !this->pkgpath_from_option_
408 && !this->prefix_from_option_);
411 // Import a package.
413 void
414 Gogo::import_package(const std::string& filename,
415 const std::string& local_name,
416 bool is_local_name_exported,
417 bool must_exist,
418 Location location)
420 if (filename.empty())
422 go_error_at(location, "import path is empty");
423 return;
426 const char *pf = filename.data();
427 const char *pend = pf + filename.length();
428 while (pf < pend)
430 unsigned int c;
431 int adv = Lex::fetch_char(pf, &c);
432 if (adv == 0)
434 go_error_at(location, "import path contains invalid UTF-8 sequence");
435 return;
437 if (c == '\0')
439 go_error_at(location, "import path contains NUL");
440 return;
442 if (c < 0x20 || c == 0x7f)
444 go_error_at(location, "import path contains control character");
445 return;
447 if (c == '\\')
449 go_error_at(location, "import path contains backslash; use slash");
450 return;
452 if (Lex::is_unicode_space(c))
454 go_error_at(location, "import path contains space character");
455 return;
457 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
459 go_error_at(location,
460 "import path contains invalid character '%c'", c);
461 return;
463 pf += adv;
466 if (IS_ABSOLUTE_PATH(filename.c_str()))
468 go_error_at(location, "import path cannot be absolute path");
469 return;
472 if (local_name == "init")
473 go_error_at(location, "cannot import package as init");
475 if (filename == "unsafe")
477 this->import_unsafe(local_name, is_local_name_exported, location);
478 this->current_file_imported_unsafe_ = true;
479 return;
482 if (filename == "embed")
483 this->current_file_imported_embed_ = true;
485 Imports::const_iterator p = this->imports_.find(filename);
486 if (p != this->imports_.end())
488 Package* package = p->second;
489 package->set_location(location);
490 std::string ln = local_name;
491 bool is_ln_exported = is_local_name_exported;
492 if (ln.empty())
494 ln = package->package_name();
495 go_assert(!ln.empty());
496 is_ln_exported = Lex::is_exported_name(ln);
498 if (ln == "_")
500 else if (ln == ".")
502 Bindings* bindings = package->bindings();
503 for (Bindings::const_declarations_iterator pd =
504 bindings->begin_declarations();
505 pd != bindings->end_declarations();
506 ++pd)
507 this->add_dot_import_object(pd->second);
508 std::string dot_alias = "." + package->package_name();
509 package->add_alias(dot_alias, location);
511 else
513 package->add_alias(ln, location);
514 ln = this->pack_hidden_name(ln, is_ln_exported);
515 this->package_->bindings()->add_package(ln, package);
517 return;
520 Import::Stream* stream = Import::open_package(filename, location,
521 this->relative_import_path_);
522 if (stream == NULL)
524 if (must_exist)
525 go_error_at(location, "import file %qs not found", filename.c_str());
526 return;
529 Import* imp = new Import(stream, location);
530 imp->register_builtin_types(this);
531 Package* package = imp->import(this, local_name, is_local_name_exported);
532 if (package != NULL)
534 if (package->pkgpath() == this->pkgpath())
535 go_error_at(location,
536 ("imported package uses same package path as package "
537 "being compiled (see %<-fgo-pkgpath%> option)"));
539 this->imports_.insert(std::make_pair(filename, package));
542 imp->clear_stream();
543 delete stream;
545 // FIXME: we never delete imp; we may need it for inlinable functions.
548 Import_init *
549 Gogo::lookup_init(const std::string& init_name)
551 Import_init tmp("", init_name, -1);
552 Import_init_set::iterator it = this->imported_init_fns_.find(&tmp);
553 return (it != this->imported_init_fns_.end()) ? *it : NULL;
556 // Add an import control function for an imported package to the list.
558 void
559 Gogo::add_import_init_fn(const std::string& package_name,
560 const std::string& init_name, int prio)
562 for (Import_init_set::iterator p =
563 this->imported_init_fns_.begin();
564 p != this->imported_init_fns_.end();
565 ++p)
567 Import_init *ii = (*p);
568 if (ii->init_name() == init_name)
570 // If a test of package P1, built as part of package P1,
571 // imports package P2, and P2 imports P1 (perhaps
572 // indirectly), then we will see the same import name with
573 // different import priorities. That is OK, so don't give
574 // an error about it.
575 if (ii->package_name() != package_name)
577 go_error_at(Linemap::unknown_location(),
578 "duplicate package initialization name %qs",
579 Gogo::message_name(init_name).c_str());
580 go_inform(Linemap::unknown_location(), "used by package %qs",
581 Gogo::message_name(ii->package_name()).c_str());
582 go_inform(Linemap::unknown_location(), " and by package %qs",
583 Gogo::message_name(package_name).c_str());
585 ii->set_priority(prio);
586 return;
590 Import_init* nii = new Import_init(package_name, init_name, prio);
591 this->imported_init_fns_.insert(nii);
594 // Return whether we are at the global binding level.
596 bool
597 Gogo::in_global_scope() const
599 return this->functions_.empty();
602 // Return the current binding contour.
604 Bindings*
605 Gogo::current_bindings()
607 if (!this->functions_.empty())
608 return this->functions_.back().blocks.back()->bindings();
609 else if (this->package_ != NULL)
610 return this->package_->bindings();
611 else
612 return this->globals_;
615 const Bindings*
616 Gogo::current_bindings() const
618 if (!this->functions_.empty())
619 return this->functions_.back().blocks.back()->bindings();
620 else if (this->package_ != NULL)
621 return this->package_->bindings();
622 else
623 return this->globals_;
626 void
627 Gogo::update_init_priority(Import_init* ii,
628 std::set<const Import_init *>* visited)
630 visited->insert(ii);
631 int succ_prior = -1;
633 for (std::set<std::string>::const_iterator pci =
634 ii->precursors().begin();
635 pci != ii->precursors().end();
636 ++pci)
638 Import_init* succ = this->lookup_init(*pci);
639 if (visited->find(succ) == visited->end())
640 update_init_priority(succ, visited);
641 succ_prior = std::max(succ_prior, succ->priority());
643 if (ii->priority() <= succ_prior)
644 ii->set_priority(succ_prior + 1);
647 void
648 Gogo::recompute_init_priorities()
650 std::set<Import_init *> nonroots;
652 for (Import_init_set::const_iterator p =
653 this->imported_init_fns_.begin();
654 p != this->imported_init_fns_.end();
655 ++p)
657 const Import_init *ii = *p;
658 for (std::set<std::string>::const_iterator pci =
659 ii->precursors().begin();
660 pci != ii->precursors().end();
661 ++pci)
663 Import_init* ii_init = this->lookup_init(*pci);
664 nonroots.insert(ii_init);
668 // Recursively update priorities starting at roots.
669 std::set<const Import_init*> visited;
670 for (Import_init_set::iterator p =
671 this->imported_init_fns_.begin();
672 p != this->imported_init_fns_.end();
673 ++p)
675 Import_init* ii = *p;
676 if (nonroots.find(ii) != nonroots.end())
677 continue;
678 update_init_priority(ii, &visited);
682 // Add statements to INIT_STMTS which run the initialization
683 // functions for imported packages. This is only used for the "main"
684 // package.
686 void
687 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction)
689 go_assert(this->is_main_package());
691 if (this->imported_init_fns_.empty())
692 return;
694 Location unknown_loc = Linemap::unknown_location();
695 Function_type* func_type =
696 Type::make_function_type(NULL, NULL, NULL, unknown_loc);
697 Btype* fntype = func_type->get_backend_fntype(this);
699 // Recompute init priorities based on a walk of the init graph.
700 recompute_init_priorities();
702 // We must call them in increasing priority order.
703 std::vector<const Import_init*> v;
704 for (Import_init_set::const_iterator p =
705 this->imported_init_fns_.begin();
706 p != this->imported_init_fns_.end();
707 ++p)
709 // Don't include dummy inits. They are not real functions.
710 if ((*p)->is_dummy())
711 continue;
712 if ((*p)->priority() < 0)
713 go_error_at(Linemap::unknown_location(),
714 "internal error: failed to set init priority for %s",
715 (*p)->package_name().c_str());
716 v.push_back(*p);
718 std::sort(v.begin(), v.end(), priority_compare);
720 // We build calls to the init functions, which take no arguments.
721 std::vector<Bexpression*> empty_args;
722 for (std::vector<const Import_init*>::const_iterator p = v.begin();
723 p != v.end();
724 ++p)
726 const Import_init* ii = *p;
727 std::string user_name = ii->package_name() + ".init";
728 const std::string& init_name(ii->init_name());
729 const unsigned int flags =
730 (Backend::function_is_visible
731 | Backend::function_is_declaration
732 | Backend::function_is_inlinable);
733 Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
734 flags, unknown_loc);
735 Bexpression* pfunc_code =
736 this->backend()->function_code_expression(pfunc, unknown_loc);
737 Bexpression* pfunc_call =
738 this->backend()->call_expression(bfunction, pfunc_code, empty_args,
739 NULL, unknown_loc);
740 init_stmts.push_back(this->backend()->expression_statement(bfunction,
741 pfunc_call));
745 // Register global variables with the garbage collector. We need to
746 // register all variables which can hold a pointer value. They become
747 // roots during the mark phase. We build a struct that is easy to
748 // hook into a list of roots.
750 // type gcRoot struct {
751 // decl unsafe.Pointer // Pointer to variable.
752 // size uintptr // Total size of variable.
753 // ptrdata uintptr // Length of variable's gcdata.
754 // gcdata *byte // Pointer mask.
755 // }
757 // type gcRootList struct {
758 // next *gcRootList
759 // count int
760 // roots [...]gcRoot
761 // }
763 // The last entry in the roots array has a NULL decl field.
765 void
766 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
767 std::vector<Bstatement*>& init_stmts,
768 Bfunction* init_bfn)
770 if (var_gc.empty() && this->gc_roots_.empty())
771 return;
773 Type* pvt = Type::make_pointer_type(Type::make_void_type());
774 Type* uintptr_type = Type::lookup_integer_type("uintptr");
775 Type* byte_type = Type::lookup_integer_type("byte");
776 Type* pointer_byte_type = Type::make_pointer_type(byte_type);
777 Struct_type* root_type =
778 Type::make_builtin_struct_type(4,
779 "decl", pvt,
780 "size", uintptr_type,
781 "ptrdata", uintptr_type,
782 "gcdata", pointer_byte_type);
784 Location builtin_loc = Linemap::predeclared_location();
785 unsigned long roots_len = var_gc.size() + this->gc_roots_.size();
786 Expression* length = Expression::make_integer_ul(roots_len, NULL,
787 builtin_loc);
788 Array_type* root_array_type = Type::make_array_type(root_type, length);
789 root_array_type->set_is_array_incomparable();
791 Type* int_type = Type::lookup_integer_type("int");
792 Struct_type* root_list_type =
793 Type::make_builtin_struct_type(3,
794 "next", pvt,
795 "count", int_type,
796 "roots", root_array_type);
798 // Build an initializer for the roots array.
800 Expression_list* roots_init = new Expression_list();
802 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
803 p != var_gc.end();
804 ++p)
806 Expression_list* init = new Expression_list();
808 Location no_loc = (*p)->location();
809 Expression* decl = Expression::make_var_reference(*p, no_loc);
810 Expression* decl_addr =
811 Expression::make_unary(OPERATOR_AND, decl, no_loc);
812 decl_addr->unary_expression()->set_does_not_escape();
813 decl_addr = Expression::make_cast(pvt, decl_addr, no_loc);
814 init->push_back(decl_addr);
816 Expression* size =
817 Expression::make_type_info(decl->type(),
818 Expression::TYPE_INFO_SIZE);
819 init->push_back(size);
821 Expression* ptrdata =
822 Expression::make_type_info(decl->type(),
823 Expression::TYPE_INFO_BACKEND_PTRDATA);
824 init->push_back(ptrdata);
826 Expression* gcdata = Expression::make_ptrmask_symbol(decl->type());
827 init->push_back(gcdata);
829 Expression* root_ctor =
830 Expression::make_struct_composite_literal(root_type, init, no_loc);
831 roots_init->push_back(root_ctor);
834 for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin();
835 p != this->gc_roots_.end();
836 ++p)
838 Expression_list *init = new Expression_list();
840 Expression* expr = *p;
841 Location eloc = expr->location();
842 init->push_back(Expression::make_cast(pvt, expr, eloc));
844 Type* type = expr->type()->points_to();
845 go_assert(type != NULL);
847 Expression* size =
848 Expression::make_type_info(type,
849 Expression::TYPE_INFO_SIZE);
850 init->push_back(size);
852 Expression* ptrdata =
853 Expression::make_type_info(type,
854 Expression::TYPE_INFO_BACKEND_PTRDATA);
855 init->push_back(ptrdata);
857 Expression* gcdata = Expression::make_ptrmask_symbol(type);
858 init->push_back(gcdata);
860 Expression* root_ctor =
861 Expression::make_struct_composite_literal(root_type, init, eloc);
862 roots_init->push_back(root_ctor);
865 // Build a constructor for the struct.
867 Expression_list* root_list_init = new Expression_list();
868 root_list_init->push_back(Expression::make_nil(builtin_loc));
869 root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type,
870 builtin_loc));
872 Expression* roots_ctor =
873 Expression::make_array_composite_literal(root_array_type, roots_init,
874 builtin_loc);
875 root_list_init->push_back(roots_ctor);
877 Expression* root_list_ctor =
878 Expression::make_struct_composite_literal(root_list_type, root_list_init,
879 builtin_loc);
881 Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
882 builtin_loc);
883 root_addr->unary_expression()->set_is_gc_root();
884 Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
885 builtin_loc, 1, root_addr);
887 Translate_context context(this, NULL, NULL, NULL);
888 Bexpression* bcall = register_roots->get_backend(&context);
889 init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall));
892 // Build the list of type descriptors defined in this package. This is to help
893 // the reflect package to find compiler-generated types.
895 // type typeDescriptorList struct {
896 // count int
897 // types [...]unsafe.Pointer
898 // }
900 static Struct_type*
901 type_descriptor_list_type(unsigned long len)
903 Location builtin_loc = Linemap::predeclared_location();
904 Type* int_type = Type::lookup_integer_type("int");
905 Type* ptr_type = Type::make_pointer_type(Type::make_void_type());
906 // Avoid creating zero-length type.
907 unsigned long nelems = (len != 0 ? len : 1);
908 Expression* len_expr = Expression::make_integer_ul(nelems, NULL,
909 builtin_loc);
910 Array_type* array_type = Type::make_array_type(ptr_type, len_expr);
911 array_type->set_is_array_incomparable();
912 Struct_type* list_type =
913 Type::make_builtin_struct_type(2, "count", int_type,
914 "types", array_type);
915 return list_type;
918 void
919 Gogo::build_type_descriptor_list()
921 // Create the list type
922 Location builtin_loc = Linemap::predeclared_location();
923 unsigned long len = this->type_descriptors_.size();
924 Struct_type* list_type = type_descriptor_list_type(len);
925 Btype* bt = list_type->get_backend(this);
926 Btype* bat = list_type->field(1)->type()->get_backend(this);
928 // Create the variable
929 std::string name = this->type_descriptor_list_symbol(this->pkgpath_symbol());
930 unsigned int flags = Backend::variable_is_constant;
931 Bvariable* bv = this->backend()->implicit_variable(name, name, bt, flags, 0);
933 // Build the initializer
934 std::vector<unsigned long> indexes;
935 std::vector<Bexpression*> vals;
936 std::vector<Type*>::iterator p = this->type_descriptors_.begin();
937 for (unsigned long i = 0; i < len; ++i, ++p)
939 Bexpression* bexpr = (*p)->type_descriptor_pointer(this,
940 builtin_loc);
941 indexes.push_back(i);
942 vals.push_back(bexpr);
944 Bexpression* barray =
945 this->backend()->array_constructor_expression(bat, indexes, vals,
946 builtin_loc);
948 Translate_context context(this, NULL, NULL, NULL);
949 std::vector<Bexpression*> fields;
950 Expression* len_expr = Expression::make_integer_ul(len, NULL,
951 builtin_loc);
952 fields.push_back(len_expr->get_backend(&context));
953 fields.push_back(barray);
954 Bexpression* binit =
955 this->backend()->constructor_expression(bt, fields, builtin_loc);
957 this->backend()->implicit_variable_set_init(bv, name, bt, flags, binit);
960 // Register the type descriptors with the runtime. This is to help
961 // the reflect package to find compiler-generated types.
963 void
964 Gogo::register_type_descriptors(std::vector<Bstatement*>& init_stmts,
965 Bfunction* init_bfn)
967 // Create the list type
968 Location builtin_loc = Linemap::predeclared_location();
969 Struct_type* list_type = type_descriptor_list_type(1);
970 Btype* bt = list_type->get_backend(this);
972 // Collect type lists from transitive imports.
973 std::vector<std::string> list_names;
974 for (Import_init_set::iterator it = this->imported_init_fns_.begin();
975 it != this->imported_init_fns_.end();
976 ++it)
978 std::string pkgpath_symbol =
979 this->pkgpath_symbol_from_init_fn_name((*it)->init_name());
980 list_names.push_back(this->type_descriptor_list_symbol(pkgpath_symbol));
982 // Add the main package itself.
983 list_names.push_back(this->type_descriptor_list_symbol("main"));
985 // Build a list of lists.
986 std::vector<unsigned long> indexes;
987 std::vector<Bexpression*> vals;
988 unsigned long i = 0;
989 for (std::vector<std::string>::iterator p = list_names.begin();
990 p != list_names.end();
991 ++p)
993 Bvariable* bv =
994 this->backend()->implicit_variable_reference(*p, *p, bt);
995 Bexpression* bexpr = this->backend()->var_expression(bv, builtin_loc);
996 bexpr = this->backend()->address_expression(bexpr, builtin_loc);
998 indexes.push_back(i);
999 vals.push_back(bexpr);
1000 i++;
1002 Expression* len_expr = Expression::make_integer_ul(i, NULL, builtin_loc);
1003 Type* list_ptr_type = Type::make_pointer_type(list_type);
1004 Type* list_array_type = Type::make_array_type(list_ptr_type, len_expr);
1005 Btype* bat = list_array_type->get_backend(this);
1006 Bexpression* barray =
1007 this->backend()->array_constructor_expression(bat, indexes, vals,
1008 builtin_loc);
1010 // Create a variable holding the list.
1011 std::string name = this->typelists_symbol();
1012 unsigned int flags = (Backend::variable_is_hidden
1013 | Backend::variable_is_constant);
1014 Bvariable* bv = this->backend()->implicit_variable(name, name, bat, flags,
1016 this->backend()->implicit_variable_set_init(bv, name, bat, flags, barray);
1018 // Build the call in main package's init function.
1019 Translate_context context(this, NULL, NULL, NULL);
1020 Bexpression* bexpr = this->backend()->var_expression(bv, builtin_loc);
1021 bexpr = this->backend()->address_expression(bexpr, builtin_loc);
1022 Type* array_ptr_type = Type::make_pointer_type(list_array_type);
1023 Expression* expr = Expression::make_backend(bexpr, array_ptr_type,
1024 builtin_loc);
1025 expr = Runtime::make_call(Runtime::REGISTER_TYPE_DESCRIPTORS,
1026 builtin_loc, 2, len_expr->copy(), expr);
1027 Bexpression* bcall = expr->get_backend(&context);
1028 init_stmts.push_back(this->backend()->expression_statement(init_bfn,
1029 bcall));
1032 // Build the decl for the initialization function.
1034 Named_object*
1035 Gogo::initialization_function_decl()
1037 std::string name = this->get_init_fn_name();
1038 Location loc = this->package_->location();
1040 Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
1041 Function* initfn = new Function(fntype, NULL, NULL, loc);
1042 return Named_object::make_function(name, NULL, initfn);
1045 // Create the magic initialization function. CODE_STMT is the
1046 // code that it needs to run.
1048 Named_object*
1049 Gogo::create_initialization_function(Named_object* initfn,
1050 Bstatement* code_stmt)
1052 // Make sure that we thought we needed an initialization function,
1053 // as otherwise we will not have reported it in the export data.
1054 go_assert(this->is_main_package() || this->need_init_fn_);
1056 if (initfn == NULL)
1057 initfn = this->initialization_function_decl();
1059 // Bind the initialization function code to a block.
1060 Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
1061 Location pkg_loc = this->package_->location();
1062 std::vector<Bvariable*> vars;
1063 this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
1065 if (!this->backend()->function_set_body(fndecl, code_stmt))
1067 go_assert(saw_errors());
1068 return NULL;
1070 return initfn;
1073 // Given an expression, collect all the global variables defined in
1074 // this package that it references.
1076 class Find_vars : public Traverse
1078 private:
1079 // The list of variables we accumulate.
1080 typedef Unordered_set(Named_object*) Vars;
1082 // A hash table we use to avoid looping. The index is a
1083 // Named_object* or a Temporary_statement*. We only look through
1084 // objects defined in this package.
1085 typedef Unordered_set(const void*) Seen_objects;
1087 public:
1088 Find_vars()
1089 : Traverse(traverse_expressions),
1090 vars_(), seen_objects_()
1093 // An iterator through the variables found, after the traversal.
1094 typedef Vars::const_iterator const_iterator;
1096 const_iterator
1097 begin() const
1098 { return this->vars_.begin(); }
1100 const_iterator
1101 end() const
1102 { return this->vars_.end(); }
1105 expression(Expression**);
1107 private:
1108 // Accumulated variables.
1109 Vars vars_;
1110 // Objects we have already seen.
1111 Seen_objects seen_objects_;
1114 // Collect global variables referenced by EXPR. Look through function
1115 // calls and variable initializations.
1118 Find_vars::expression(Expression** pexpr)
1120 Expression* e = *pexpr;
1122 Var_expression* ve = e->var_expression();
1123 if (ve != NULL)
1125 Named_object* v = ve->named_object();
1126 if (!v->is_variable() || v->package() != NULL)
1128 // This is a result parameter or a variable defined in a
1129 // different package. Either way we don't care about it.
1130 return TRAVERSE_CONTINUE;
1133 std::pair<Seen_objects::iterator, bool> ins =
1134 this->seen_objects_.insert(v);
1135 if (!ins.second)
1137 // We've seen this variable before.
1138 return TRAVERSE_CONTINUE;
1141 if (v->var_value()->is_global())
1142 this->vars_.insert(v);
1144 Expression* init = v->var_value()->init();
1145 if (init != NULL)
1147 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1148 return TRAVERSE_EXIT;
1152 // We traverse the code of any function or bound method we see. Note that
1153 // this means that we will traverse the code of a function or bound method
1154 // whose address is taken even if it is not called.
1155 Func_expression* fe = e->func_expression();
1156 Bound_method_expression* bme = e->bound_method_expression();
1157 if (fe != NULL || bme != NULL)
1159 const Named_object* f = fe != NULL ? fe->named_object() : bme->function();
1160 if (f->is_function() && f->package() == NULL)
1162 std::pair<Seen_objects::iterator, bool> ins =
1163 this->seen_objects_.insert(f);
1164 if (ins.second)
1166 // This is the first time we have seen this name.
1167 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
1168 return TRAVERSE_EXIT;
1173 Temporary_reference_expression* tre = e->temporary_reference_expression();
1174 if (tre != NULL)
1176 Temporary_statement* ts = tre->statement();
1177 Expression* init = ts->init();
1178 if (init != NULL)
1180 std::pair<Seen_objects::iterator, bool> ins =
1181 this->seen_objects_.insert(ts);
1182 if (ins.second)
1184 // This is the first time we have seen this temporary
1185 // statement.
1186 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1187 return TRAVERSE_EXIT;
1192 return TRAVERSE_CONTINUE;
1195 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1197 static bool
1198 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1199 Named_object* var)
1201 Find_vars find_vars;
1202 if (expr != NULL)
1203 Expression::traverse(&expr, &find_vars);
1204 if (preinit != NULL)
1205 preinit->traverse(&find_vars);
1206 if (dep != NULL)
1208 Expression* init = dep->var_value()->init();
1209 if (init != NULL)
1210 Expression::traverse(&init, &find_vars);
1211 if (dep->var_value()->has_pre_init())
1212 dep->var_value()->preinit()->traverse(&find_vars);
1215 for (Find_vars::const_iterator p = find_vars.begin();
1216 p != find_vars.end();
1217 ++p)
1219 if (*p == var)
1220 return true;
1222 return false;
1225 // Sort variable initializations. If the initialization expression
1226 // for variable A refers directly or indirectly to the initialization
1227 // expression for variable B, then we must initialize B before A.
1229 class Var_init
1231 public:
1232 Var_init()
1233 : var_(NULL), init_(NULL), refs_(NULL), dep_count_(0)
1236 Var_init(Named_object* var, Bstatement* init)
1237 : var_(var), init_(init), refs_(NULL), dep_count_(0)
1240 // Return the variable.
1241 Named_object*
1242 var() const
1243 { return this->var_; }
1245 // Return the initialization expression.
1246 Bstatement*
1247 init() const
1248 { return this->init_; }
1250 // Add a reference.
1251 void
1252 add_ref(Named_object* var);
1254 // The variables which this variable's initializers refer to.
1255 const std::vector<Named_object*>*
1256 refs()
1257 { return this->refs_; }
1259 // Clear the references, if any.
1260 void
1261 clear_refs();
1263 // Return the number of remaining dependencies.
1264 size_t
1265 dep_count() const
1266 { return this->dep_count_; }
1268 // Increment the number of dependencies.
1269 void
1270 add_dependency()
1271 { ++this->dep_count_; }
1273 // Decrement the number of dependencies.
1274 void
1275 remove_dependency()
1276 { --this->dep_count_; }
1278 private:
1279 // The variable being initialized.
1280 Named_object* var_;
1281 // The backend initialization statement.
1282 Bstatement* init_;
1283 // Variables this refers to.
1284 std::vector<Named_object*>* refs_;
1285 // The number of initializations this is dependent on. A variable
1286 // initialization should not be emitted if any of its dependencies
1287 // have not yet been resolved.
1288 size_t dep_count_;
1291 // Add a reference.
1293 void
1294 Var_init::add_ref(Named_object* var)
1296 if (this->refs_ == NULL)
1297 this->refs_ = new std::vector<Named_object*>;
1298 this->refs_->push_back(var);
1301 // Clear the references, if any.
1303 void
1304 Var_init::clear_refs()
1306 if (this->refs_ != NULL)
1308 delete this->refs_;
1309 this->refs_ = NULL;
1313 // For comparing Var_init keys in a map.
1315 inline bool
1316 operator<(const Var_init& v1, const Var_init& v2)
1317 { return v1.var()->name() < v2.var()->name(); }
1319 typedef std::list<Var_init> Var_inits;
1321 // Sort the variable initializations. The rule we follow is that we
1322 // emit them in the order they appear in the array, except that if the
1323 // initialization expression for a variable V1 depends upon another
1324 // variable V2 then we initialize V1 after V2.
1326 static void
1327 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1329 if (var_inits->empty())
1330 return;
1332 std::map<Named_object*, Var_init*> var_to_init;
1334 // A mapping from a variable initialization to a set of
1335 // variable initializations that depend on it.
1336 typedef std::map<Var_init, std::set<Var_init*> > Init_deps;
1337 Init_deps init_deps;
1338 bool init_loop = false;
1340 // Compute all variable references.
1341 for (Var_inits::iterator pvar = var_inits->begin();
1342 pvar != var_inits->end();
1343 ++pvar)
1345 Named_object* var = pvar->var();
1346 var_to_init[var] = &*pvar;
1348 Find_vars find_vars;
1349 Expression* init = var->var_value()->init();
1350 if (init != NULL)
1351 Expression::traverse(&init, &find_vars);
1352 if (var->var_value()->has_pre_init())
1353 var->var_value()->preinit()->traverse(&find_vars);
1354 Named_object* dep = gogo->var_depends_on(var->var_value());
1355 if (dep != NULL)
1357 Expression* dinit = dep->var_value()->init();
1358 if (dinit != NULL)
1359 Expression::traverse(&dinit, &find_vars);
1360 if (dep->var_value()->has_pre_init())
1361 dep->var_value()->preinit()->traverse(&find_vars);
1363 for (Find_vars::const_iterator p = find_vars.begin();
1364 p != find_vars.end();
1365 ++p)
1366 pvar->add_ref(*p);
1369 // Add dependencies to init_deps, and check for cycles.
1370 for (Var_inits::iterator pvar = var_inits->begin();
1371 pvar != var_inits->end();
1372 ++pvar)
1374 Named_object* var = pvar->var();
1376 const std::vector<Named_object*>* refs = pvar->refs();
1377 if (refs == NULL)
1378 continue;
1379 for (std::vector<Named_object*>::const_iterator pdep = refs->begin();
1380 pdep != refs->end();
1381 ++pdep)
1383 Named_object* dep = *pdep;
1384 if (var == dep)
1386 // This is a reference from a variable to itself, which
1387 // may indicate a loop. We only report an error if
1388 // there is an initializer and there is no dependency.
1389 // When there is no initializer, it means that the
1390 // preinitializer sets the variable, which will appear
1391 // to be a loop here.
1392 if (var->var_value()->init() != NULL
1393 && gogo->var_depends_on(var->var_value()) == NULL)
1394 go_error_at(var->location(),
1395 ("initialization expression for %qs "
1396 "depends upon itself"),
1397 var->message_name().c_str());
1399 continue;
1402 Var_init* dep_init = var_to_init[dep];
1403 if (dep_init == NULL)
1405 // This is a dependency on some variable that doesn't
1406 // have an initializer, so for purposes of
1407 // initialization ordering this is irrelevant.
1408 continue;
1411 init_deps[*dep_init].insert(&(*pvar));
1412 pvar->add_dependency();
1414 // Check for cycles.
1415 const std::vector<Named_object*>* deprefs = dep_init->refs();
1416 if (deprefs == NULL)
1417 continue;
1418 for (std::vector<Named_object*>::const_iterator pdepdep =
1419 deprefs->begin();
1420 pdepdep != deprefs->end();
1421 ++pdepdep)
1423 if (*pdepdep == var)
1425 go_error_at(var->location(),
1426 ("initialization expressions for %qs and "
1427 "%qs depend upon each other"),
1428 var->message_name().c_str(),
1429 dep->message_name().c_str());
1430 go_inform(dep->location(), "%qs defined here",
1431 dep->message_name().c_str());
1432 init_loop = true;
1433 break;
1439 var_to_init.clear();
1440 for (Var_inits::iterator pvar = var_inits->begin();
1441 pvar != var_inits->end();
1442 ++pvar)
1443 pvar->clear_refs();
1445 // If there are no dependencies then the declaration order is sorted.
1446 if (!init_deps.empty() && !init_loop)
1448 // Otherwise, sort variable initializations by emitting all variables with
1449 // no dependencies in declaration order. VAR_INITS is already in
1450 // declaration order.
1451 Var_inits ready;
1452 while (!var_inits->empty())
1454 Var_inits::iterator v1;;
1455 for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1)
1457 if (v1->dep_count() == 0)
1458 break;
1460 go_assert(v1 != var_inits->end());
1462 // V1 either has no dependencies or its dependencies have already
1463 // been emitted, add it to READY next. When V1 is emitted, remove
1464 // a dependency from each V that depends on V1.
1465 ready.splice(ready.end(), *var_inits, v1);
1467 Init_deps::iterator p1 = init_deps.find(*v1);
1468 if (p1 != init_deps.end())
1470 std::set<Var_init*> resolved = p1->second;
1471 for (std::set<Var_init*>::iterator pv = resolved.begin();
1472 pv != resolved.end();
1473 ++pv)
1474 (*pv)->remove_dependency();
1475 init_deps.erase(p1);
1478 var_inits->swap(ready);
1479 go_assert(init_deps.empty());
1483 // Give an error if the initialization expression for VAR depends on
1484 // itself. We only check if INIT is not NULL and there is no
1485 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1486 // which we will interpret as a loop.
1488 void
1489 Gogo::check_self_dep(Named_object* var)
1491 Expression* init = var->var_value()->init();
1492 Block* preinit = var->var_value()->preinit();
1493 Named_object* dep = this->var_depends_on(var->var_value());
1494 if (init != NULL
1495 && dep == NULL
1496 && expression_requires(init, preinit, NULL, var))
1497 go_error_at(var->location(),
1498 "initialization expression for %qs depends upon itself",
1499 var->message_name().c_str());
1502 // Write out the global definitions.
1504 void
1505 Gogo::write_globals()
1507 this->build_interface_method_tables();
1509 Bindings* bindings = this->current_bindings();
1511 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1512 p != bindings->end_declarations();
1513 ++p)
1515 // If any function declarations needed a descriptor, make sure
1516 // we build it.
1517 Named_object* no = p->second;
1518 if (no->is_function_declaration())
1519 no->func_declaration_value()->build_backend_descriptor(this);
1522 // Lists of globally declared types, variables, constants, and functions
1523 // that must be defined.
1524 std::vector<Btype*> type_decls;
1525 std::vector<Bvariable*> var_decls;
1526 std::vector<Bexpression*> const_decls;
1527 std::vector<Bfunction*> func_decls;
1529 // The init function declaration and associated Bfunction, if necessary.
1530 Named_object* init_fndecl = NULL;
1531 Bfunction* init_bfn = NULL;
1533 std::vector<Bstatement*> init_stmts;
1534 std::vector<Bstatement*> var_init_stmts;
1536 if (this->is_main_package())
1538 init_fndecl = this->initialization_function_decl();
1539 init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl);
1542 // A list of variable initializations.
1543 Var_inits var_inits;
1545 // A list of variables which need to be registered with the garbage
1546 // collector.
1547 size_t count_definitions = bindings->size_definitions();
1548 std::vector<Named_object*> var_gc;
1549 var_gc.reserve(count_definitions);
1551 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1552 p != bindings->end_definitions();
1553 ++p)
1555 Named_object* no = *p;
1556 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1558 // There is nothing to do for a package.
1559 if (no->is_package())
1560 continue;
1562 // There is nothing to do for an object which was imported from
1563 // a different package into the global scope.
1564 if (no->package() != NULL)
1565 continue;
1567 // Skip blank named functions and constants.
1568 if ((no->is_function() && no->func_value()->is_sink())
1569 || (no->is_const() && no->const_value()->is_sink()))
1570 continue;
1572 // Skip global sink variables with static initializers. With
1573 // non-static initializers we have to evaluate for side effects,
1574 // and we wind up initializing a dummy variable. That is not
1575 // ideal but it works and it's a rare case.
1576 if (no->is_variable()
1577 && no->var_value()->is_global_sink()
1578 && !no->var_value()->has_pre_init()
1579 && (no->var_value()->init() == NULL
1580 || no->var_value()->init()->is_static_initializer()))
1581 continue;
1583 // There is nothing useful we can output for constants which
1584 // have ideal or non-integral type.
1585 if (no->is_const())
1587 Type* type = no->const_value()->type();
1588 if (type == NULL)
1589 type = no->const_value()->expr()->type();
1590 if (type->is_abstract() || !type->is_numeric_type())
1591 continue;
1594 if (!no->is_variable())
1595 no->get_backend(this, const_decls, type_decls, func_decls);
1596 else
1598 Variable* var = no->var_value();
1599 Bvariable* bvar = no->get_backend_variable(this, NULL);
1600 var_decls.push_back(bvar);
1602 // Check for a sink variable, which may be used to run an
1603 // initializer purely for its side effects.
1604 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1606 Bstatement* var_init_stmt = NULL;
1607 if (!var->has_pre_init())
1609 // If the backend representation of the variable initializer is
1610 // constant, we can just set the initial value using
1611 // global_var_set_init instead of during the init() function.
1612 // The initializer is constant if it is the zero-value of the
1613 // variable's type or if the initial value is an immutable value
1614 // that is not copied to the heap.
1615 bool is_static_initializer = false;
1616 if (var->init() == NULL)
1617 is_static_initializer = true;
1618 else
1620 Type* var_type = var->type();
1621 Expression* init = var->init();
1622 Expression* init_cast =
1623 Expression::make_cast(var_type, init, var->location());
1624 is_static_initializer = init_cast->is_static_initializer();
1627 // Non-constant variable initializations might need to create
1628 // temporary variables, which will need the initialization
1629 // function as context.
1630 Named_object* var_init_fn;
1631 if (is_static_initializer)
1632 var_init_fn = NULL;
1633 else
1635 if (init_fndecl == NULL)
1637 init_fndecl = this->initialization_function_decl();
1638 Function* func = init_fndecl->func_value();
1639 init_bfn = func->get_or_make_decl(this, init_fndecl);
1641 var_init_fn = init_fndecl;
1643 Bexpression* var_binit = var->get_init(this, var_init_fn);
1645 if (var_binit == NULL)
1647 else if (is_static_initializer)
1649 if (expression_requires(var->init(), NULL,
1650 this->var_depends_on(var), no))
1651 go_error_at(no->location(),
1652 "initialization expression for %qs depends "
1653 "upon itself",
1654 no->message_name().c_str());
1655 this->backend()->global_variable_set_init(bvar, var_binit);
1657 else if (is_sink)
1658 var_init_stmt =
1659 this->backend()->expression_statement(init_bfn, var_binit);
1660 else
1662 Location loc = var->location();
1663 Bexpression* var_expr =
1664 this->backend()->var_expression(bvar, loc);
1665 var_init_stmt =
1666 this->backend()->assignment_statement(init_bfn, var_expr,
1667 var_binit, loc);
1670 else
1672 // We are going to create temporary variables which
1673 // means that we need an fndecl.
1674 if (init_fndecl == NULL)
1675 init_fndecl = this->initialization_function_decl();
1677 Bvariable* var_decl = is_sink ? NULL : bvar;
1678 var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1681 if (var_init_stmt != NULL)
1683 if (var->init() == NULL && !var->has_pre_init())
1684 var_init_stmts.push_back(var_init_stmt);
1685 else
1686 var_inits.push_back(Var_init(no, var_init_stmt));
1688 else if (this->var_depends_on(var) != NULL)
1690 // This variable is initialized from something that is
1691 // not in its init or preinit. This variable needs to
1692 // participate in dependency analysis sorting, in case
1693 // some other variable depends on this one.
1694 Btype* btype = no->var_value()->type()->get_backend(this);
1695 Bexpression* zero = this->backend()->zero_expression(btype);
1696 Bstatement* zero_stmt =
1697 this->backend()->expression_statement(init_bfn, zero);
1698 var_inits.push_back(Var_init(no, zero_stmt));
1701 // Collect a list of all global variables with pointers,
1702 // to register them for the garbage collector.
1703 if (!is_sink && var->type()->has_pointer())
1705 // Avoid putting runtime.gcRoots itself on the list.
1706 if (this->compiling_runtime()
1707 && this->package_name() == "runtime"
1708 && (Gogo::unpack_hidden_name(no->name()) == "gcRoots"
1709 || Gogo::unpack_hidden_name(no->name()) == "gcRootsIndex"))
1711 else
1712 var_gc.push_back(no);
1717 // Output inline functions, which are in different packages.
1718 for (std::vector<Named_object*>::const_iterator p =
1719 this->imported_inline_functions_.begin();
1720 p != this->imported_inline_functions_.end();
1721 ++p)
1722 (*p)->get_backend(this, const_decls, type_decls, func_decls);
1724 // Build the list of type descriptors.
1725 this->build_type_descriptor_list();
1727 if (this->is_main_package())
1729 // Register the type descriptor lists, so that at run time
1730 // the reflect package can find compiler-created types, and
1731 // deduplicate if the same type is created with reflection.
1732 // This needs to be done before calling any package's init
1733 // function, as it may create type through reflection.
1734 this->register_type_descriptors(init_stmts, init_bfn);
1736 // Initialize imported packages.
1737 this->init_imports(init_stmts, init_bfn);
1740 // Register global variables with the garbage collector.
1741 this->register_gc_vars(var_gc, init_stmts, init_bfn);
1743 // Simple variable initializations, after all variables are
1744 // registered.
1745 init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1747 // Complete variable initializations, first sorting them into a
1748 // workable order.
1749 if (!var_inits.empty())
1751 sort_var_inits(this, &var_inits);
1752 for (Var_inits::const_iterator p = var_inits.begin();
1753 p != var_inits.end();
1754 ++p)
1755 init_stmts.push_back(p->init());
1758 // After all the variables are initialized, call the init
1759 // functions if there are any. Init functions take no arguments, so
1760 // we pass in EMPTY_ARGS to call them.
1761 std::vector<Bexpression*> empty_args;
1762 for (std::vector<Named_object*>::const_iterator p =
1763 this->init_functions_.begin();
1764 p != this->init_functions_.end();
1765 ++p)
1767 Location func_loc = (*p)->location();
1768 Function* func = (*p)->func_value();
1769 Bfunction* initfn = func->get_or_make_decl(this, *p);
1770 Bexpression* func_code =
1771 this->backend()->function_code_expression(initfn, func_loc);
1772 Bexpression* call = this->backend()->call_expression(init_bfn, func_code,
1773 empty_args,
1774 NULL, func_loc);
1775 Bstatement* ist = this->backend()->expression_statement(init_bfn, call);
1776 init_stmts.push_back(ist);
1779 // Set up a magic function to do all the initialization actions.
1780 // This will be called if this package is imported.
1781 Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1782 if (this->need_init_fn_ || this->is_main_package())
1784 init_fndecl =
1785 this->create_initialization_function(init_fndecl, init_fncode);
1786 if (init_fndecl != NULL)
1787 func_decls.push_back(init_fndecl->func_value()->get_decl());
1790 // We should not have seen any new bindings created during the conversion.
1791 go_assert(count_definitions == this->current_bindings()->size_definitions());
1793 // Define all globally declared values.
1794 if (!saw_errors())
1795 this->backend()->write_global_definitions(type_decls, const_decls,
1796 func_decls, var_decls);
1799 // Return the current block.
1801 Block*
1802 Gogo::current_block()
1804 if (this->functions_.empty())
1805 return NULL;
1806 else
1807 return this->functions_.back().blocks.back();
1810 // Look up a name in the current binding contour. If PFUNCTION is not
1811 // NULL, set it to the function in which the name is defined, or NULL
1812 // if the name is defined in global scope.
1814 Named_object*
1815 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1817 if (pfunction != NULL)
1818 *pfunction = NULL;
1820 if (Gogo::is_sink_name(name))
1821 return Named_object::make_sink();
1823 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1824 p != this->functions_.rend();
1825 ++p)
1827 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1828 if (ret != NULL)
1830 if (pfunction != NULL)
1831 *pfunction = p->function;
1832 return ret;
1836 if (this->package_ != NULL)
1838 Named_object* ret = this->package_->bindings()->lookup(name);
1839 if (ret != NULL)
1841 if (ret->package() != NULL)
1843 std::string dot_alias = "." + ret->package()->package_name();
1844 ret->package()->note_usage(dot_alias);
1846 return ret;
1850 // We do not look in the global namespace. If we did, the global
1851 // namespace would effectively hide names which were defined in
1852 // package scope which we have not yet seen. Instead,
1853 // define_global_names is called after parsing is over to connect
1854 // undefined names at package scope with names defined at global
1855 // scope.
1857 return NULL;
1860 // Look up a name in the current block, without searching enclosing
1861 // blocks.
1863 Named_object*
1864 Gogo::lookup_in_block(const std::string& name) const
1866 go_assert(!this->functions_.empty());
1867 go_assert(!this->functions_.back().blocks.empty());
1868 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1871 // Look up a name in the global namespace.
1873 Named_object*
1874 Gogo::lookup_global(const char* name) const
1876 return this->globals_->lookup(name);
1879 // Add an imported package.
1881 Package*
1882 Gogo::add_imported_package(const std::string& real_name,
1883 const std::string& alias_arg,
1884 bool is_alias_exported,
1885 const std::string& pkgpath,
1886 const std::string& pkgpath_symbol,
1887 Location location,
1888 bool* padd_to_globals)
1890 Package* ret = this->register_package(pkgpath, pkgpath_symbol, location);
1891 ret->set_package_name(real_name, location);
1893 *padd_to_globals = false;
1895 if (alias_arg == "_")
1897 else if (alias_arg == ".")
1899 *padd_to_globals = true;
1900 std::string dot_alias = "." + real_name;
1901 ret->add_alias(dot_alias, location);
1903 else
1905 std::string alias = alias_arg;
1906 if (alias.empty())
1908 alias = real_name;
1909 is_alias_exported = Lex::is_exported_name(alias);
1911 ret->add_alias(alias, location);
1912 alias = this->pack_hidden_name(alias, is_alias_exported);
1913 Named_object* no = this->package_->bindings()->add_package(alias, ret);
1914 if (!no->is_package())
1915 return NULL;
1918 return ret;
1921 // Register a package. This package may or may not be imported. This
1922 // returns the Package structure for the package, creating if it
1923 // necessary. LOCATION is the location of the import statement that
1924 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1925 // for names in the package; it may be the empty string, in which case
1926 // we either get it later or make a guess when we need it.
1928 Package*
1929 Gogo::register_package(const std::string& pkgpath,
1930 const std::string& pkgpath_symbol, Location location)
1932 Package* package = NULL;
1933 std::pair<Packages::iterator, bool> ins =
1934 this->packages_.insert(std::make_pair(pkgpath, package));
1935 if (!ins.second)
1937 // We have seen this package name before.
1938 package = ins.first->second;
1939 go_assert(package != NULL && package->pkgpath() == pkgpath);
1940 if (!pkgpath_symbol.empty())
1941 package->set_pkgpath_symbol(pkgpath_symbol);
1942 if (Linemap::is_unknown_location(package->location()))
1943 package->set_location(location);
1945 else
1947 // First time we have seen this package name.
1948 package = new Package(pkgpath, pkgpath_symbol, location);
1949 go_assert(ins.first->second == NULL);
1950 ins.first->second = package;
1953 return package;
1956 // Return the pkgpath symbol for a package, given the pkgpath.
1958 std::string
1959 Gogo::pkgpath_symbol_for_package(const std::string& pkgpath)
1961 Packages::iterator p = this->packages_.find(pkgpath);
1962 go_assert(p != this->packages_.end());
1963 return p->second->pkgpath_symbol();
1966 // Start compiling a function.
1968 Named_object*
1969 Gogo::start_function(const std::string& name, Function_type* type,
1970 bool add_method_to_type, Location location)
1972 bool at_top_level = this->functions_.empty();
1974 Block* block = new Block(NULL, location);
1976 Named_object* enclosing = (at_top_level
1977 ? NULL
1978 : this->functions_.back().function);
1980 Function* function = new Function(type, enclosing, block, location);
1982 if (type->is_method())
1984 const Typed_identifier* receiver = type->receiver();
1985 Variable* this_param = new Variable(receiver->type(), NULL, false,
1986 true, true, location);
1987 std::string rname = receiver->name();
1988 unsigned rcounter = 0;
1990 // We need to give a nameless receiver parameter a synthesized name to
1991 // avoid having it clash with some other nameless param. FIXME.
1992 Gogo::rename_if_empty(&rname, "r", &rcounter);
1994 block->bindings()->add_variable(rname, NULL, this_param);
1997 const Typed_identifier_list* parameters = type->parameters();
1998 bool is_varargs = type->is_varargs();
1999 unsigned pcounter = 0;
2000 if (parameters != NULL)
2002 for (Typed_identifier_list::const_iterator p = parameters->begin();
2003 p != parameters->end();
2004 ++p)
2006 Variable* param = new Variable(p->type(), NULL, false, true, false,
2007 p->location());
2008 if (is_varargs && p + 1 == parameters->end())
2009 param->set_is_varargs_parameter();
2011 std::string pname = p->name();
2013 // We need to give each nameless parameter a non-empty name to avoid
2014 // having it clash with some other nameless param. FIXME.
2015 Gogo::rename_if_empty(&pname, "p", &pcounter);
2017 block->bindings()->add_variable(pname, NULL, param);
2021 function->create_result_variables(this);
2023 const std::string* pname;
2024 std::string nested_name;
2025 bool is_init = false;
2026 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
2028 if ((type->parameters() != NULL && !type->parameters()->empty())
2029 || (type->results() != NULL && !type->results()->empty()))
2030 go_error_at(location,
2031 "func init must have no arguments and no return values");
2032 // There can be multiple "init" functions, so give them each a
2033 // different name.
2034 nested_name = this->init_function_name();
2035 pname = &nested_name;
2036 is_init = true;
2038 else if (!name.empty())
2039 pname = &name;
2040 else
2042 // Invent a name for a nested function.
2043 nested_name = this->nested_function_name(enclosing);
2044 pname = &nested_name;
2047 Named_object* ret;
2048 if (Gogo::is_sink_name(*pname))
2050 std::string sname(this->sink_function_name());
2051 ret = Named_object::make_function(sname, NULL, function);
2052 ret->func_value()->set_is_sink();
2054 if (!type->is_method())
2055 ret = this->package_->bindings()->add_named_object(ret);
2056 else if (add_method_to_type)
2058 // We should report errors even for sink methods.
2059 Type* rtype = type->receiver()->type();
2060 // Avoid points_to and deref to avoid getting an error if
2061 // the type is not yet defined.
2062 if (rtype->classification() == Type::TYPE_POINTER)
2063 rtype = rtype->points_to();
2064 while (rtype->named_type() != NULL
2065 && rtype->named_type()->is_alias())
2066 rtype = rtype->named_type()->real_type()->forwarded();
2067 if (rtype->is_error_type())
2069 else if (rtype->named_type() != NULL)
2071 if (rtype->named_type()->named_object()->package() != NULL)
2072 go_error_at(type->receiver()->location(),
2073 "may not define methods on non-local type");
2075 else if (rtype->forward_declaration_type() != NULL)
2077 // Go ahead and add the method in case we need to report
2078 // an error when we see the definition.
2079 rtype->forward_declaration_type()->add_existing_method(ret);
2081 else
2082 go_error_at(type->receiver()->location(),
2083 ("invalid receiver type "
2084 "(receiver must be a named type)"));
2087 else if (!type->is_method())
2089 ret = this->package_->bindings()->add_function(*pname, NULL, function);
2090 if (!ret->is_function() || ret->func_value() != function)
2092 // Redefinition error. Invent a name to avoid knockon
2093 // errors.
2094 std::string rname(this->redefined_function_name());
2095 ret = this->package_->bindings()->add_function(rname, NULL, function);
2098 else
2100 if (!add_method_to_type)
2101 ret = Named_object::make_function(name, NULL, function);
2102 else
2104 go_assert(at_top_level);
2105 Type* rtype = type->receiver()->type();
2107 while (rtype->named_type() != NULL
2108 && rtype->named_type()->is_alias())
2109 rtype = rtype->named_type()->real_type()->forwarded();
2111 // We want to look through the pointer created by the
2112 // parser, without getting an error if the type is not yet
2113 // defined.
2114 if (rtype->classification() == Type::TYPE_POINTER)
2115 rtype = rtype->points_to();
2117 while (rtype->named_type() != NULL
2118 && rtype->named_type()->is_alias())
2119 rtype = rtype->named_type()->real_type()->forwarded();
2121 if (rtype->is_error_type())
2122 ret = Named_object::make_function(name, NULL, function);
2123 else if (rtype->named_type() != NULL)
2125 if (rtype->named_type()->named_object()->package() != NULL)
2127 go_error_at(type->receiver()->location(),
2128 "may not define methods on non-local type");
2129 ret = Named_object::make_function(name, NULL, function);
2131 else
2133 ret = rtype->named_type()->add_method(name, function);
2134 if (!ret->is_function())
2136 // Redefinition error.
2137 ret = Named_object::make_function(name, NULL, function);
2141 else if (rtype->forward_declaration_type() != NULL)
2143 Named_object* type_no =
2144 rtype->forward_declaration_type()->named_object();
2145 if (type_no->is_unknown())
2147 // If we are seeing methods it really must be a
2148 // type. Declare it as such. An alternative would
2149 // be to support lists of methods for unknown
2150 // expressions. Either way the error messages if
2151 // this is not a type are going to get confusing.
2152 Named_object* declared =
2153 this->declare_package_type(type_no->name(),
2154 type_no->location());
2155 go_assert(declared
2156 == type_no->unknown_value()->real_named_object());
2158 ret = rtype->forward_declaration_type()->add_method(name,
2159 function);
2161 else
2163 go_error_at(type->receiver()->location(),
2164 ("invalid receiver type (receiver must "
2165 "be a named type)"));
2166 ret = Named_object::make_function(name, NULL, function);
2169 this->package_->bindings()->add_method(ret);
2172 this->functions_.resize(this->functions_.size() + 1);
2173 Open_function& of(this->functions_.back());
2174 of.function = ret;
2175 of.blocks.push_back(block);
2177 if (is_init)
2179 this->init_functions_.push_back(ret);
2180 this->need_init_fn_ = true;
2183 return ret;
2186 // Finish compiling a function.
2188 void
2189 Gogo::finish_function(Location location)
2191 this->finish_block(location);
2192 go_assert(this->functions_.back().blocks.empty());
2193 this->functions_.pop_back();
2196 // Return the current function.
2198 Named_object*
2199 Gogo::current_function() const
2201 go_assert(!this->functions_.empty());
2202 return this->functions_.back().function;
2205 // Start a new block.
2207 void
2208 Gogo::start_block(Location location)
2210 go_assert(!this->functions_.empty());
2211 Block* block = new Block(this->current_block(), location);
2212 this->functions_.back().blocks.push_back(block);
2215 // Finish a block.
2217 Block*
2218 Gogo::finish_block(Location location)
2220 go_assert(!this->functions_.empty());
2221 go_assert(!this->functions_.back().blocks.empty());
2222 Block* block = this->functions_.back().blocks.back();
2223 this->functions_.back().blocks.pop_back();
2224 block->set_end_location(location);
2225 return block;
2228 // Add an erroneous name.
2230 Named_object*
2231 Gogo::add_erroneous_name(const std::string& name)
2233 return this->package_->bindings()->add_erroneous_name(name);
2236 // Add an unknown name.
2238 Named_object*
2239 Gogo::add_unknown_name(const std::string& name, Location location)
2241 return this->package_->bindings()->add_unknown_name(name, location);
2244 // Declare a function.
2246 Named_object*
2247 Gogo::declare_function(const std::string& name, Function_type* type,
2248 Location location)
2250 if (!type->is_method())
2251 return this->current_bindings()->add_function_declaration(name, NULL, type,
2252 location);
2253 else
2255 // We don't bother to add this to the list of global
2256 // declarations.
2257 Type* rtype = type->receiver()->type();
2259 while (rtype->named_type() != NULL
2260 && rtype->named_type()->is_alias())
2261 rtype = rtype->named_type()->real_type()->forwarded();
2263 // We want to look through the pointer created by the
2264 // parser, without getting an error if the type is not yet
2265 // defined.
2266 if (rtype->classification() == Type::TYPE_POINTER)
2267 rtype = rtype->points_to();
2269 while (rtype->named_type() != NULL
2270 && rtype->named_type()->is_alias())
2271 rtype = rtype->named_type()->real_type()->forwarded();
2273 if (rtype->is_error_type())
2274 return NULL;
2275 else if (rtype->named_type() != NULL)
2276 return rtype->named_type()->add_method_declaration(name, NULL, type,
2277 location);
2278 else if (rtype->forward_declaration_type() != NULL)
2280 Forward_declaration_type* ftype = rtype->forward_declaration_type();
2281 return ftype->add_method_declaration(name, NULL, type, location);
2283 else
2285 go_error_at(type->receiver()->location(),
2286 "invalid receiver type (receiver must be a named type)");
2287 return Named_object::make_erroneous_name(name);
2292 // Add a label definition.
2294 Label*
2295 Gogo::add_label_definition(const std::string& label_name,
2296 Location location)
2298 go_assert(!this->functions_.empty());
2299 Function* func = this->functions_.back().function->func_value();
2300 Label* label = func->add_label_definition(this, label_name, location);
2301 this->add_statement(Statement::make_label_statement(label, location));
2302 return label;
2305 // Add a label reference.
2307 Label*
2308 Gogo::add_label_reference(const std::string& label_name,
2309 Location location, bool issue_goto_errors)
2311 go_assert(!this->functions_.empty());
2312 Function* func = this->functions_.back().function->func_value();
2313 return func->add_label_reference(this, label_name, location,
2314 issue_goto_errors);
2317 // Return the current binding state.
2319 Bindings_snapshot*
2320 Gogo::bindings_snapshot(Location location)
2322 return new Bindings_snapshot(this->current_block(), location);
2325 // Add a statement.
2327 void
2328 Gogo::add_statement(Statement* statement)
2330 go_assert(!this->functions_.empty()
2331 && !this->functions_.back().blocks.empty());
2332 this->functions_.back().blocks.back()->add_statement(statement);
2335 // Add a block.
2337 void
2338 Gogo::add_block(Block* block, Location location)
2340 go_assert(!this->functions_.empty()
2341 && !this->functions_.back().blocks.empty());
2342 Statement* statement = Statement::make_block_statement(block, location);
2343 this->functions_.back().blocks.back()->add_statement(statement);
2346 // Add a constant.
2348 Named_object*
2349 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
2350 int iota_value)
2352 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
2355 // Add a type.
2357 void
2358 Gogo::add_type(const std::string& name, Type* type, Location location)
2360 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
2361 location);
2362 if (!this->in_global_scope() && no->is_type())
2364 Named_object* f = this->functions_.back().function;
2365 unsigned int index;
2366 if (f->is_function())
2367 index = f->func_value()->new_local_type_index();
2368 else
2369 index = 0;
2370 no->type_value()->set_in_function(f, index);
2374 // Add a named type.
2376 void
2377 Gogo::add_named_type(Named_type* type)
2379 go_assert(this->in_global_scope());
2380 this->current_bindings()->add_named_type(type);
2383 // Declare a type.
2385 Named_object*
2386 Gogo::declare_type(const std::string& name, Location location)
2388 Bindings* bindings = this->current_bindings();
2389 Named_object* no = bindings->add_type_declaration(name, NULL, location);
2390 if (!this->in_global_scope() && no->is_type_declaration())
2392 Named_object* f = this->functions_.back().function;
2393 unsigned int index;
2394 if (f->is_function())
2395 index = f->func_value()->new_local_type_index();
2396 else
2397 index = 0;
2398 no->type_declaration_value()->set_in_function(f, index);
2400 return no;
2403 // Declare a type at the package level.
2405 Named_object*
2406 Gogo::declare_package_type(const std::string& name, Location location)
2408 return this->package_->bindings()->add_type_declaration(name, NULL, location);
2411 // Declare a function at the package level.
2413 Named_object*
2414 Gogo::declare_package_function(const std::string& name, Function_type* type,
2415 Location location)
2417 return this->package_->bindings()->add_function_declaration(name, NULL, type,
2418 location);
2421 // Add a function declaration to the list of functions we may want to
2422 // inline.
2424 void
2425 Gogo::add_imported_inlinable_function(Named_object* no)
2427 go_assert(no->is_function_declaration());
2428 Function_declaration* fd = no->func_declaration_value();
2429 if (fd->is_on_inlinable_list())
2430 return;
2431 this->imported_inlinable_functions_.push_back(no);
2432 fd->set_is_on_inlinable_list();
2435 // Define a type which was already declared.
2437 void
2438 Gogo::define_type(Named_object* no, Named_type* type)
2440 this->current_bindings()->define_type(no, type);
2443 // Add a variable.
2445 Named_object*
2446 Gogo::add_variable(const std::string& name, Variable* variable)
2448 Named_object* no = this->current_bindings()->add_variable(name, NULL,
2449 variable);
2451 // In a function the middle-end wants to see a DECL_EXPR node.
2452 if (no != NULL
2453 && no->is_variable()
2454 && !no->var_value()->is_parameter()
2455 && !this->functions_.empty())
2456 this->add_statement(Statement::make_variable_declaration(no));
2458 return no;
2461 void
2462 Gogo::rename_if_empty(std::string* pname, const char* tag, unsigned* count)
2464 if (pname->empty() || Gogo::is_sink_name(*pname))
2466 char buf[50];
2467 go_assert(strlen(tag) < 10);
2468 snprintf(buf, sizeof buf, "%s.%u", tag, *count);
2469 ++(*count);
2470 *pname = buf;
2475 // Add a sink--a reference to the blank identifier _.
2477 Named_object*
2478 Gogo::add_sink()
2480 return Named_object::make_sink();
2483 // Add a named object for a dot import.
2485 void
2486 Gogo::add_dot_import_object(Named_object* no)
2488 // If the name already exists, then it was defined in some file seen
2489 // earlier. If the earlier name is just a declaration, don't add
2490 // this name, because that will cause the previous declaration to
2491 // merge to this imported name, which should not happen. Just add
2492 // this name to the list of file block names to get appropriate
2493 // errors if we see a later definition.
2494 Named_object* e = this->package_->bindings()->lookup(no->name());
2495 if (e != NULL && e->package() == NULL)
2497 if (e->is_unknown())
2498 e = e->resolve();
2499 if (e->package() == NULL
2500 && (e->is_type_declaration()
2501 || e->is_function_declaration()
2502 || e->is_unknown()))
2504 this->add_file_block_name(no->name(), no->location());
2505 return;
2509 this->current_bindings()->add_named_object(no);
2512 // Add a linkname. This implements the go:linkname compiler directive.
2513 // We only support this for functions and function declarations.
2515 void
2516 Gogo::add_linkname(const std::string& go_name, bool is_exported,
2517 const std::string& ext_name, Location loc)
2519 Named_object* no =
2520 this->package_->bindings()->lookup(this->pack_hidden_name(go_name,
2521 is_exported));
2522 if (no == NULL)
2523 go_error_at(loc, "%s is not defined", go_name.c_str());
2524 else if (no->is_function())
2526 if (ext_name.empty())
2527 no->func_value()->set_is_exported_by_linkname();
2528 else
2529 no->func_value()->set_asm_name(ext_name);
2531 else if (no->is_function_declaration())
2533 if (ext_name.empty())
2534 go_error_at(loc,
2535 ("%<//go:linkname%> missing external name "
2536 "for declaration of %s"),
2537 go_name.c_str());
2538 else
2539 no->func_declaration_value()->set_asm_name(ext_name);
2541 else
2542 go_error_at(loc,
2543 ("%s is not a function; "
2544 "%<//go:linkname%> is only supported for functions"),
2545 go_name.c_str());
2548 // Mark all local variables used. This is used when some types of
2549 // parse error occur.
2551 void
2552 Gogo::mark_locals_used()
2554 for (Open_functions::iterator pf = this->functions_.begin();
2555 pf != this->functions_.end();
2556 ++pf)
2558 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2559 pb != pf->blocks.end();
2560 ++pb)
2561 (*pb)->bindings()->mark_locals_used();
2565 // Record that we've seen an interface type.
2567 void
2568 Gogo::record_interface_type(Interface_type* itype)
2570 this->interface_types_.push_back(itype);
2573 // Define the global names. We do this only after parsing all the
2574 // input files, because the program might define the global names
2575 // itself.
2577 void
2578 Gogo::define_global_names()
2580 if (this->is_main_package())
2582 // Every Go program has to import the runtime package, so that
2583 // it is properly initialized. We can't use
2584 // predeclared_location here as it will cause runtime functions
2585 // to appear to be builtin functions.
2586 this->import_package("runtime", "_", false, false,
2587 this->package_->location());
2590 for (Bindings::const_declarations_iterator p =
2591 this->globals_->begin_declarations();
2592 p != this->globals_->end_declarations();
2593 ++p)
2595 Named_object* global_no = p->second;
2596 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2597 Named_object* no = this->package_->bindings()->lookup(name);
2598 if (no == NULL)
2599 continue;
2600 no = no->resolve();
2601 if (no->is_type_declaration())
2603 if (global_no->is_type())
2605 if (no->type_declaration_value()->has_methods())
2607 for (std::vector<Named_object*>::const_iterator pm =
2608 no->type_declaration_value()->methods()->begin();
2609 pm != no->type_declaration_value()->methods()->end();
2610 pm++)
2611 go_error_at((*pm)->location(),
2612 "may not define methods on non-local type");
2614 no->set_type_value(global_no->type_value());
2616 else
2618 go_error_at(no->location(), "expected type");
2619 Type* errtype = Type::make_error_type();
2620 Named_object* err =
2621 Named_object::make_type("erroneous_type", NULL, errtype,
2622 Linemap::predeclared_location());
2623 no->set_type_value(err->type_value());
2626 else if (no->is_unknown())
2627 no->unknown_value()->set_real_named_object(global_no);
2630 // Give an error if any name is defined in both the package block
2631 // and the file block. For example, this can happen if one file
2632 // imports "fmt" and another file defines a global variable fmt.
2633 for (Bindings::const_declarations_iterator p =
2634 this->package_->bindings()->begin_declarations();
2635 p != this->package_->bindings()->end_declarations();
2636 ++p)
2638 if (p->second->is_unknown()
2639 && p->second->unknown_value()->real_named_object() == NULL)
2641 // No point in warning about an undefined name, as we will
2642 // get other errors later anyhow.
2643 continue;
2645 File_block_names::const_iterator pf =
2646 this->file_block_names_.find(p->second->name());
2647 if (pf != this->file_block_names_.end())
2649 std::string n = p->second->message_name();
2650 go_error_at(p->second->location(),
2651 "%qs defined as both imported name and global name",
2652 n.c_str());
2653 go_inform(pf->second, "%qs imported here", n.c_str());
2656 // No package scope identifier may be named "init".
2657 if (!p->second->is_function()
2658 && Gogo::unpack_hidden_name(p->second->name()) == "init")
2660 go_error_at(p->second->location(),
2661 "cannot declare init - must be func");
2666 // Clear out names in file scope.
2668 void
2669 Gogo::clear_file_scope()
2671 this->package_->bindings()->clear_file_scope(this);
2673 // Warn about packages which were imported but not used.
2674 bool quiet = saw_errors();
2675 for (Packages::iterator p = this->packages_.begin();
2676 p != this->packages_.end();
2677 ++p)
2679 Package* package = p->second;
2680 if (package != this->package_ && !quiet)
2682 for (Package::Aliases::const_iterator p1 = package->aliases().begin();
2683 p1 != package->aliases().end();
2684 ++p1)
2686 if (!p1->second->used())
2688 // Give a more refined error message if the alias name is known.
2689 std::string pkg_name = package->package_name();
2690 if (p1->first != pkg_name && p1->first[0] != '.')
2692 go_error_at(p1->second->location(),
2693 "imported and not used: %s as %s",
2694 Gogo::message_name(pkg_name).c_str(),
2695 Gogo::message_name(p1->first).c_str());
2697 else
2698 go_error_at(p1->second->location(),
2699 "imported and not used: %s",
2700 Gogo::message_name(pkg_name).c_str());
2704 package->clear_used();
2707 this->current_file_imported_unsafe_ = false;
2708 this->current_file_imported_embed_ = false;
2711 // Queue up a type-specific hash function for later writing. These
2712 // are written out in write_specific_type_functions, called after the
2713 // parse tree is lowered.
2715 void
2716 Gogo::queue_hash_function(Type* type, int64_t size, Backend_name* bname,
2717 Function_type* hash_fntype)
2719 go_assert(!this->specific_type_functions_are_written_);
2720 go_assert(!this->in_global_scope());
2721 Specific_type_function::Specific_type_function_kind kind =
2722 Specific_type_function::SPECIFIC_HASH;
2723 Specific_type_function* tsf = new Specific_type_function(type, NULL, size,
2724 kind, bname,
2725 hash_fntype);
2726 this->specific_type_functions_.push_back(tsf);
2729 // Queue up a type-specific equal function for later writing. These
2730 // are written out in write_specific_type_functions, called after the
2731 // parse tree is lowered.
2733 void
2734 Gogo::queue_equal_function(Type* type, Named_type* name, int64_t size,
2735 Backend_name* bname, Function_type* equal_fntype)
2737 go_assert(!this->specific_type_functions_are_written_);
2738 go_assert(!this->in_global_scope());
2739 Specific_type_function::Specific_type_function_kind kind =
2740 Specific_type_function::SPECIFIC_EQUAL;
2741 Specific_type_function* tsf = new Specific_type_function(type, name, size,
2742 kind, bname,
2743 equal_fntype);
2744 this->specific_type_functions_.push_back(tsf);
2747 // Look for types which need specific hash or equality functions.
2749 class Specific_type_functions : public Traverse
2751 public:
2752 Specific_type_functions(Gogo* gogo)
2753 : Traverse(traverse_types),
2754 gogo_(gogo)
2758 type(Type*);
2760 private:
2761 Gogo* gogo_;
2765 Specific_type_functions::type(Type* t)
2767 switch (t->classification())
2769 case Type::TYPE_NAMED:
2771 Named_type* nt = t->named_type();
2772 if (nt->is_alias())
2773 return TRAVERSE_CONTINUE;
2774 if (t->needs_specific_type_functions(this->gogo_))
2775 t->equal_function(this->gogo_, nt, NULL);
2777 // If this is a struct type, we don't want to make functions
2778 // for the unnamed struct.
2779 Type* rt = nt->real_type();
2780 if (rt->struct_type() == NULL)
2782 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2783 return TRAVERSE_EXIT;
2785 else
2787 // If this type is defined in another package, then we don't
2788 // need to worry about the unexported fields.
2789 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2790 const Struct_field_list* fields = rt->struct_type()->fields();
2791 for (Struct_field_list::const_iterator p = fields->begin();
2792 p != fields->end();
2793 ++p)
2795 if (is_defined_elsewhere
2796 && Gogo::is_hidden_name(p->field_name()))
2797 continue;
2798 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2799 return TRAVERSE_EXIT;
2803 return TRAVERSE_SKIP_COMPONENTS;
2806 case Type::TYPE_STRUCT:
2807 case Type::TYPE_ARRAY:
2808 if (t->needs_specific_type_functions(this->gogo_))
2809 t->equal_function(this->gogo_, NULL, NULL);
2810 break;
2812 case Type::TYPE_MAP:
2814 Type* key_type = t->map_type()->key_type();
2815 if (key_type->needs_specific_type_functions(this->gogo_))
2816 key_type->hash_function(this->gogo_, NULL);
2818 break;
2820 default:
2821 break;
2824 return TRAVERSE_CONTINUE;
2827 // Write out type specific functions.
2829 void
2830 Gogo::write_specific_type_functions()
2832 Specific_type_functions stf(this);
2833 this->traverse(&stf);
2835 while (!this->specific_type_functions_.empty())
2837 Specific_type_function* tsf = this->specific_type_functions_.back();
2838 this->specific_type_functions_.pop_back();
2839 if (tsf->kind == Specific_type_function::SPECIFIC_HASH)
2840 tsf->type->write_hash_function(this, tsf->size, &tsf->bname,
2841 tsf->fntype);
2842 else
2843 tsf->type->write_equal_function(this, tsf->name, tsf->size,
2844 &tsf->bname, tsf->fntype);
2845 delete tsf;
2847 this->specific_type_functions_are_written_ = true;
2850 // Traverse the tree.
2852 void
2853 Gogo::traverse(Traverse* traverse)
2855 // Traverse the current package first for consistency. The other
2856 // packages will only contain imported types, constants, and
2857 // declarations.
2858 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2859 return;
2860 for (Packages::const_iterator p = this->packages_.begin();
2861 p != this->packages_.end();
2862 ++p)
2864 if (p->second != this->package_)
2866 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2867 break;
2872 // Add a type to verify. This is used for types of sink variables, in
2873 // order to give appropriate error messages.
2875 void
2876 Gogo::add_type_to_verify(Type* type)
2878 this->verify_types_.push_back(type);
2881 // Traversal class used to verify types.
2883 class Verify_types : public Traverse
2885 public:
2886 Verify_types()
2887 : Traverse(traverse_types)
2891 type(Type*);
2894 // Verify that a type is correct.
2897 Verify_types::type(Type* t)
2899 if (!t->verify())
2900 return TRAVERSE_SKIP_COMPONENTS;
2901 return TRAVERSE_CONTINUE;
2904 // Verify that all types are correct.
2906 void
2907 Gogo::verify_types()
2909 Verify_types traverse;
2910 this->traverse(&traverse);
2912 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2913 p != this->verify_types_.end();
2914 ++p)
2915 (*p)->verify();
2916 this->verify_types_.clear();
2919 // Traversal class used to lower parse tree.
2921 class Lower_parse_tree : public Traverse
2923 public:
2924 Lower_parse_tree(Gogo* gogo, Named_object* function)
2925 : Traverse(traverse_variables
2926 | traverse_constants
2927 | traverse_functions
2928 | traverse_statements
2929 | traverse_expressions),
2930 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2933 void
2934 set_inserter(const Statement_inserter* inserter)
2935 { this->inserter_ = *inserter; }
2938 variable(Named_object*);
2941 constant(Named_object*, bool);
2944 function(Named_object*);
2947 statement(Block*, size_t* pindex, Statement*);
2950 expression(Expression**);
2952 private:
2953 // General IR.
2954 Gogo* gogo_;
2955 // The function we are traversing.
2956 Named_object* function_;
2957 // Value to use for the predeclared constant iota.
2958 int iota_value_;
2959 // Current statement inserter for use by expressions.
2960 Statement_inserter inserter_;
2963 // Lower variables.
2966 Lower_parse_tree::variable(Named_object* no)
2968 if (!no->is_variable())
2969 return TRAVERSE_CONTINUE;
2971 if (no->is_variable() && no->var_value()->is_global())
2973 // Global variables can have loops in their initialization
2974 // expressions. This is handled in lower_init_expression.
2975 no->var_value()->lower_init_expression(this->gogo_, this->function_,
2976 &this->inserter_);
2977 return TRAVERSE_CONTINUE;
2980 // This is a local variable. We are going to return
2981 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2982 // initialization expression when we reach the variable declaration
2983 // statement. However, that means that we need to traverse the type
2984 // ourselves.
2985 if (no->var_value()->has_type())
2987 Type* type = no->var_value()->type();
2988 if (type != NULL)
2990 if (Type::traverse(type, this) == TRAVERSE_EXIT)
2991 return TRAVERSE_EXIT;
2994 go_assert(!no->var_value()->has_pre_init());
2996 return TRAVERSE_SKIP_COMPONENTS;
2999 // Lower constants. We handle constants specially so that we can set
3000 // the right value for the predeclared constant iota. This works in
3001 // conjunction with the way we lower Const_expression objects.
3004 Lower_parse_tree::constant(Named_object* no, bool)
3006 Named_constant* nc = no->const_value();
3008 // Don't get into trouble if the constant's initializer expression
3009 // refers to the constant itself.
3010 if (nc->lowering())
3011 return TRAVERSE_CONTINUE;
3012 nc->set_lowering();
3014 go_assert(this->iota_value_ == -1);
3015 this->iota_value_ = nc->iota_value();
3016 nc->traverse_expression(this);
3017 this->iota_value_ = -1;
3019 nc->clear_lowering();
3021 // We will traverse the expression a second time, but that will be
3022 // fast.
3024 return TRAVERSE_CONTINUE;
3027 // Lower the body of a function, and set the closure type. Record the
3028 // function while lowering it, so that we can pass it down when
3029 // lowering an expression.
3032 Lower_parse_tree::function(Named_object* no)
3034 no->func_value()->set_closure_type();
3036 go_assert(this->function_ == NULL);
3037 this->function_ = no;
3038 int t = no->func_value()->traverse(this);
3039 this->function_ = NULL;
3041 if (t == TRAVERSE_EXIT)
3042 return t;
3043 return TRAVERSE_SKIP_COMPONENTS;
3046 // Lower statement parse trees.
3049 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
3051 // Because we explicitly traverse the statement's contents
3052 // ourselves, we want to skip block statements here. There is
3053 // nothing to lower in a block statement.
3054 if (sorig->is_block_statement())
3055 return TRAVERSE_CONTINUE;
3057 Statement_inserter hold_inserter(this->inserter_);
3058 this->inserter_ = Statement_inserter(block, pindex);
3060 // Lower the expressions first.
3061 int t = sorig->traverse_contents(this);
3062 if (t == TRAVERSE_EXIT)
3064 this->inserter_ = hold_inserter;
3065 return t;
3068 // Keep lowering until nothing changes.
3069 Statement* s = sorig;
3070 while (true)
3072 Statement* snew = s->lower(this->gogo_, this->function_, block,
3073 &this->inserter_);
3074 if (snew == s)
3075 break;
3076 s = snew;
3077 t = s->traverse_contents(this);
3078 if (t == TRAVERSE_EXIT)
3080 this->inserter_ = hold_inserter;
3081 return t;
3085 if (s != sorig)
3086 block->replace_statement(*pindex, s);
3088 this->inserter_ = hold_inserter;
3089 return TRAVERSE_SKIP_COMPONENTS;
3092 // Lower expression parse trees.
3095 Lower_parse_tree::expression(Expression** pexpr)
3097 // We have to lower all subexpressions first, so that we can get
3098 // their type if necessary. This is awkward, because we don't have
3099 // a postorder traversal pass.
3100 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3101 return TRAVERSE_EXIT;
3102 // Keep lowering until nothing changes.
3103 while (true)
3105 Expression* e = *pexpr;
3106 Expression* enew = e->lower(this->gogo_, this->function_,
3107 &this->inserter_, this->iota_value_);
3108 if (enew == e)
3109 break;
3110 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
3111 return TRAVERSE_EXIT;
3112 *pexpr = enew;
3115 // Lower the type of this expression before the parent looks at it,
3116 // in case the type contains an array that has expressions in its
3117 // length. Skip an Unknown_expression, as at this point that means
3118 // a composite literal key that does not have a type.
3119 if ((*pexpr)->unknown_expression() == NULL)
3120 Type::traverse((*pexpr)->type(), this);
3122 return TRAVERSE_SKIP_COMPONENTS;
3125 // Lower the parse tree. This is called after the parse is complete,
3126 // when all names should be resolved.
3128 void
3129 Gogo::lower_parse_tree()
3131 Lower_parse_tree lower_parse_tree(this, NULL);
3132 this->traverse(&lower_parse_tree);
3134 // If we found any functions defined in other packages that are
3135 // inlinables, import their bodies and turn them into functions.
3137 // Note that as we import inlinable functions we may find more
3138 // inlinable functions, so don't use an iterator.
3139 for (size_t i = 0; i < this->imported_inlinable_functions_.size(); i++)
3141 Named_object* no = this->imported_inlinable_functions_[i];
3142 no->func_declaration_value()->import_function_body(this, no);
3145 // There might be type definitions that involve expressions such as the
3146 // array length. Make sure to lower these expressions as well. Otherwise,
3147 // errors hidden within a type can introduce unexpected errors into later
3148 // passes.
3149 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
3150 p != this->verify_types_.end();
3151 ++p)
3152 Type::traverse(*p, &lower_parse_tree);
3155 // Lower a block.
3157 void
3158 Gogo::lower_block(Named_object* function, Block* block)
3160 Lower_parse_tree lower_parse_tree(this, function);
3161 block->traverse(&lower_parse_tree);
3164 // Lower an expression. INSERTER may be NULL, in which case the
3165 // expression had better not need to create any temporaries.
3167 void
3168 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
3169 Expression** pexpr)
3171 Lower_parse_tree lower_parse_tree(this, function);
3172 if (inserter != NULL)
3173 lower_parse_tree.set_inserter(inserter);
3174 lower_parse_tree.expression(pexpr);
3177 // Lower a constant. This is called when lowering a reference to a
3178 // constant. We have to make sure that the constant has already been
3179 // lowered.
3181 void
3182 Gogo::lower_constant(Named_object* no)
3184 go_assert(no->is_const());
3185 Lower_parse_tree lower(this, NULL);
3186 lower.constant(no, false);
3189 // Make implicit type conversions explicit. Currently only does for
3190 // interface conversions, so the escape analysis can see them and
3191 // optimize.
3193 class Add_conversions : public Traverse
3195 public:
3196 Add_conversions()
3197 : Traverse(traverse_statements
3198 | traverse_expressions)
3202 statement(Block*, size_t* pindex, Statement*);
3205 expression(Expression**);
3208 // Add explicit conversions in a statement.
3211 Add_conversions::statement(Block*, size_t*, Statement* sorig)
3213 sorig->add_conversions();
3214 return TRAVERSE_CONTINUE;
3217 // Add explicit conversions in an expression.
3220 Add_conversions::expression(Expression** pexpr)
3222 (*pexpr)->add_conversions();
3223 return TRAVERSE_CONTINUE;
3226 void
3227 Gogo::add_conversions()
3229 Add_conversions add_conversions;
3230 this->traverse(&add_conversions);
3233 void
3234 Gogo::add_conversions_in_block(Block *b)
3236 Add_conversions add_conversions;
3237 b->traverse(&add_conversions);
3240 // Traversal class for simple deadcode elimination.
3242 class Remove_deadcode : public Traverse
3244 public:
3245 Remove_deadcode()
3246 : Traverse(traverse_statements
3247 | traverse_expressions)
3251 statement(Block*, size_t* pindex, Statement*);
3254 expression(Expression**);
3257 // Remove deadcode in a statement.
3260 Remove_deadcode::statement(Block* block, size_t* pindex, Statement* sorig)
3262 Location loc = sorig->location();
3263 If_statement* ifs = sorig->if_statement();
3264 if (ifs != NULL)
3266 // Remove the dead branch of an if statement.
3267 bool bval;
3268 if (ifs->condition()->boolean_constant_value(&bval))
3270 Statement* s;
3271 if (bval)
3272 s = Statement::make_block_statement(ifs->then_block(),
3273 loc);
3274 else
3275 if (ifs->else_block() != NULL)
3276 s = Statement::make_block_statement(ifs->else_block(),
3277 loc);
3278 else
3279 // Make a dummy statement.
3280 s = Statement::make_statement(Expression::make_boolean(false, loc),
3281 true);
3283 block->replace_statement(*pindex, s);
3286 return TRAVERSE_CONTINUE;
3289 // Remove deadcode in an expression.
3292 Remove_deadcode::expression(Expression** pexpr)
3294 // Discard the right arm of a shortcut expression of constant value.
3295 Binary_expression* be = (*pexpr)->binary_expression();
3296 bool bval;
3297 if (be != NULL
3298 && be->boolean_constant_value(&bval)
3299 && (be->op() == OPERATOR_ANDAND
3300 || be->op() == OPERATOR_OROR))
3302 *pexpr = Expression::make_boolean(bval, be->location());
3303 Type_context context(NULL, false);
3304 (*pexpr)->determine_type(&context);
3306 return TRAVERSE_CONTINUE;
3309 // Remove deadcode.
3311 void
3312 Gogo::remove_deadcode()
3314 Remove_deadcode remove_deadcode;
3315 this->traverse(&remove_deadcode);
3318 // Traverse the tree to create function descriptors as needed.
3320 class Create_function_descriptors : public Traverse
3322 public:
3323 Create_function_descriptors(Gogo* gogo)
3324 : Traverse(traverse_functions | traverse_expressions),
3325 gogo_(gogo)
3329 function(Named_object*);
3332 expression(Expression**);
3334 private:
3335 Gogo* gogo_;
3338 // Create a descriptor for every top-level exported function and every
3339 // function referenced by an inline function.
3342 Create_function_descriptors::function(Named_object* no)
3344 if (no->is_function()
3345 && no->func_value()->enclosing() == NULL
3346 && !no->func_value()->is_method()
3347 && ((!Gogo::is_hidden_name(no->name())
3348 && !Gogo::is_thunk(no))
3349 || no->func_value()->is_referenced_by_inline()))
3350 no->func_value()->descriptor(this->gogo_, no);
3352 return TRAVERSE_CONTINUE;
3355 // If we see a function referenced in any way other than calling it,
3356 // create a descriptor for it.
3359 Create_function_descriptors::expression(Expression** pexpr)
3361 Expression* expr = *pexpr;
3363 Func_expression* fe = expr->func_expression();
3364 if (fe != NULL)
3366 // We would not get here for a call to this function, so this is
3367 // a reference to a function other than calling it. We need a
3368 // descriptor.
3369 if (fe->closure() != NULL)
3370 return TRAVERSE_CONTINUE;
3371 Named_object* no = fe->named_object();
3372 if (no->is_function() && !no->func_value()->is_method())
3373 no->func_value()->descriptor(this->gogo_, no);
3374 else if (no->is_function_declaration()
3375 && !no->func_declaration_value()->type()->is_method()
3376 && !Linemap::is_predeclared_location(no->location()))
3377 no->func_declaration_value()->descriptor(this->gogo_, no);
3378 return TRAVERSE_CONTINUE;
3381 Bound_method_expression* bme = expr->bound_method_expression();
3382 if (bme != NULL)
3384 // We would not get here for a call to this method, so this is a
3385 // method value. We need to create a thunk.
3386 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
3387 bme->function());
3388 return TRAVERSE_CONTINUE;
3391 Interface_field_reference_expression* ifre =
3392 expr->interface_field_reference_expression();
3393 if (ifre != NULL)
3395 // We would not get here for a call to this interface method, so
3396 // this is a method value. We need to create a thunk.
3397 Interface_type* type = ifre->expr()->type()->interface_type();
3398 if (type != NULL)
3399 Interface_field_reference_expression::create_thunk(this->gogo_, type,
3400 ifre->name());
3401 return TRAVERSE_CONTINUE;
3404 Call_expression* ce = expr->call_expression();
3405 if (ce != NULL)
3407 Expression* fn = ce->fn();
3408 if (fn->func_expression() != NULL
3409 || fn->bound_method_expression() != NULL
3410 || fn->interface_field_reference_expression() != NULL)
3412 // Traverse the arguments but not the function.
3413 Expression_list* args = ce->args();
3414 if (args != NULL)
3416 if (args->traverse(this) == TRAVERSE_EXIT)
3417 return TRAVERSE_EXIT;
3420 // Traverse the subexpressions of the function, if any.
3421 if (fn->traverse_subexpressions(this) == TRAVERSE_EXIT)
3422 return TRAVERSE_EXIT;
3424 return TRAVERSE_SKIP_COMPONENTS;
3428 return TRAVERSE_CONTINUE;
3431 // Create function descriptors as needed. We need a function
3432 // descriptor for all exported functions and for all functions that
3433 // are referenced without being called.
3435 void
3436 Gogo::create_function_descriptors()
3438 // Create a function descriptor for any exported function that is
3439 // declared in this package. This is so that we have a descriptor
3440 // for functions written in assembly. Gather the descriptors first
3441 // so that we don't add declarations while looping over them.
3442 std::vector<Named_object*> fndecls;
3443 Bindings* b = this->package_->bindings();
3444 for (Bindings::const_declarations_iterator p = b->begin_declarations();
3445 p != b->end_declarations();
3446 ++p)
3448 Named_object* no = p->second;
3449 if (no->is_function_declaration()
3450 && !no->func_declaration_value()->type()->is_method()
3451 && !Linemap::is_predeclared_location(no->location())
3452 && !Gogo::is_hidden_name(no->name()))
3453 fndecls.push_back(no);
3455 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
3456 p != fndecls.end();
3457 ++p)
3458 (*p)->func_declaration_value()->descriptor(this, *p);
3459 fndecls.clear();
3461 Create_function_descriptors cfd(this);
3462 this->traverse(&cfd);
3465 // Finalize the methods of an interface type.
3468 Finalize_methods::type(Type* t)
3470 // Check the classification so that we don't finalize the methods
3471 // twice for a named interface type.
3472 switch (t->classification())
3474 case Type::TYPE_INTERFACE:
3475 t->interface_type()->finalize_methods();
3476 break;
3478 case Type::TYPE_NAMED:
3480 Named_type* nt = t->named_type();
3482 if (nt->is_alias())
3483 return TRAVERSE_CONTINUE;
3485 Type* rt = nt->real_type();
3486 if (rt->classification() != Type::TYPE_STRUCT)
3488 // Finalize the methods of the real type first.
3489 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
3490 return TRAVERSE_EXIT;
3492 // Finalize the methods of this type.
3493 nt->finalize_methods(this->gogo_);
3495 else
3497 // We don't want to finalize the methods of a named struct
3498 // type, as the methods should be attached to the named
3499 // type, not the struct type. We just want to finalize
3500 // the field types.
3502 // It is possible that a field type refers indirectly to
3503 // this type, such as via a field with function type with
3504 // an argument or result whose type is this type. To
3505 // avoid the cycle, first finalize the methods of any
3506 // embedded types, which are the only types we need to
3507 // know to finalize the methods of this type.
3508 const Struct_field_list* fields = rt->struct_type()->fields();
3509 if (fields != NULL)
3511 for (Struct_field_list::const_iterator pf = fields->begin();
3512 pf != fields->end();
3513 ++pf)
3515 if (pf->is_anonymous())
3517 if (Type::traverse(pf->type(), this) == TRAVERSE_EXIT)
3518 return TRAVERSE_EXIT;
3523 // Finalize the methods of this type.
3524 nt->finalize_methods(this->gogo_);
3526 // Finalize all the struct fields.
3527 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3528 return TRAVERSE_EXIT;
3531 // If this type is defined in a different package, then finalize the
3532 // types of all the methods, since we won't see them otherwise.
3533 if (nt->named_object()->package() != NULL && nt->has_any_methods())
3535 const Methods* methods = nt->methods();
3536 for (Methods::const_iterator p = methods->begin();
3537 p != methods->end();
3538 ++p)
3540 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3541 return TRAVERSE_EXIT;
3545 // Finalize the types of all methods that are declared but not
3546 // defined, since we won't see the declarations otherwise.
3547 if (nt->named_object()->package() == NULL
3548 && nt->local_methods() != NULL)
3550 const Bindings* methods = nt->local_methods();
3551 for (Bindings::const_declarations_iterator p =
3552 methods->begin_declarations();
3553 p != methods->end_declarations();
3554 p++)
3556 if (p->second->is_function_declaration())
3558 Type* mt = p->second->func_declaration_value()->type();
3559 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3560 return TRAVERSE_EXIT;
3565 return TRAVERSE_SKIP_COMPONENTS;
3568 case Type::TYPE_STRUCT:
3569 // Traverse the field types first in case there is an embedded
3570 // field with methods that the struct should inherit.
3571 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3572 return TRAVERSE_EXIT;
3573 t->struct_type()->finalize_methods(this->gogo_);
3574 return TRAVERSE_SKIP_COMPONENTS;
3576 default:
3577 break;
3580 return TRAVERSE_CONTINUE;
3583 // Finalize method lists and build stub methods for types.
3585 void
3586 Gogo::finalize_methods()
3588 Finalize_methods finalize(this);
3589 this->traverse(&finalize);
3592 // Finalize the method list for a type. This is called when a type is
3593 // parsed for an inlined function body, which happens after the
3594 // finalize_methods pass.
3596 void
3597 Gogo::finalize_methods_for_type(Type* type)
3599 Finalize_methods finalize(this);
3600 Type::traverse(type, &finalize);
3603 // Set types for unspecified variables and constants.
3605 void
3606 Gogo::determine_types()
3608 Bindings* bindings = this->current_bindings();
3609 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3610 p != bindings->end_definitions();
3611 ++p)
3613 if ((*p)->is_function())
3614 (*p)->func_value()->determine_types();
3615 else if ((*p)->is_variable())
3616 (*p)->var_value()->determine_type();
3617 else if ((*p)->is_const())
3618 (*p)->const_value()->determine_type();
3620 // See if a variable requires us to build an initialization
3621 // function. We know that we will see all global variables
3622 // here.
3623 if (!this->need_init_fn_ && (*p)->is_variable())
3625 Variable* variable = (*p)->var_value();
3627 // If this is a global variable which requires runtime
3628 // initialization, we need an initialization function.
3629 if (!variable->is_global())
3631 else if (variable->init() == NULL)
3633 else if (variable->type()->interface_type() != NULL)
3634 this->need_init_fn_ = true;
3635 else if (variable->init()->is_constant())
3637 else if (!variable->init()->is_composite_literal())
3638 this->need_init_fn_ = true;
3639 else if (variable->init()->is_nonconstant_composite_literal())
3640 this->need_init_fn_ = true;
3642 // If this is a global variable which holds a pointer value,
3643 // then we need an initialization function to register it as a
3644 // GC root.
3645 if (variable->is_global() && variable->type()->has_pointer())
3646 this->need_init_fn_ = true;
3650 // Determine the types of constants in packages.
3651 for (Packages::const_iterator p = this->packages_.begin();
3652 p != this->packages_.end();
3653 ++p)
3654 p->second->determine_types();
3657 // Traversal class used for type checking.
3659 class Check_types_traverse : public Traverse
3661 public:
3662 Check_types_traverse(Gogo* gogo)
3663 : Traverse(traverse_variables
3664 | traverse_constants
3665 | traverse_functions
3666 | traverse_statements
3667 | traverse_expressions),
3668 gogo_(gogo)
3672 variable(Named_object*);
3675 constant(Named_object*, bool);
3678 function(Named_object*);
3681 statement(Block*, size_t* pindex, Statement*);
3684 expression(Expression**);
3686 private:
3687 // General IR.
3688 Gogo* gogo_;
3691 // Check that a variable initializer has the right type.
3694 Check_types_traverse::variable(Named_object* named_object)
3696 if (named_object->is_variable())
3698 Variable* var = named_object->var_value();
3700 // Give error if variable type is not defined.
3701 var->type()->base();
3703 Expression* init = var->init();
3704 std::string reason;
3705 if (init != NULL
3706 && !Type::are_assignable(var->type(), init->type(), &reason))
3708 if (reason.empty())
3709 go_error_at(var->location(), "incompatible type in initialization");
3710 else
3711 go_error_at(var->location(),
3712 "incompatible type in initialization (%s)",
3713 reason.c_str());
3714 init = Expression::make_error(named_object->location());
3715 var->clear_init();
3717 else if (init != NULL
3718 && init->func_expression() != NULL)
3720 Named_object* no = init->func_expression()->named_object();
3721 Function_type* fntype;
3722 if (no->is_function())
3723 fntype = no->func_value()->type();
3724 else if (no->is_function_declaration())
3725 fntype = no->func_declaration_value()->type();
3726 else
3727 go_unreachable();
3729 // Builtin functions cannot be used as function values for variable
3730 // initialization.
3731 if (fntype->is_builtin())
3733 go_error_at(init->location(),
3734 "invalid use of special built-in function %qs; "
3735 "must be called",
3736 no->message_name().c_str());
3739 if (!var->is_used()
3740 && !var->is_global()
3741 && !var->is_parameter()
3742 && !var->is_receiver()
3743 && !var->type()->is_error()
3744 && (init == NULL || !init->is_error_expression())
3745 && !Lex::is_invalid_identifier(named_object->name()))
3746 go_error_at(var->location(), "%qs declared but not used",
3747 named_object->message_name().c_str());
3749 return TRAVERSE_CONTINUE;
3752 // Check that a constant initializer has the right type.
3755 Check_types_traverse::constant(Named_object* named_object, bool)
3757 Named_constant* constant = named_object->const_value();
3758 Type* ctype = constant->type();
3759 if (ctype->integer_type() == NULL
3760 && ctype->float_type() == NULL
3761 && ctype->complex_type() == NULL
3762 && !ctype->is_boolean_type()
3763 && !ctype->is_string_type())
3765 if (ctype->is_nil_type())
3766 go_error_at(constant->location(), "const initializer cannot be nil");
3767 else if (!ctype->is_error())
3768 go_error_at(constant->location(), "invalid constant type");
3769 constant->set_error();
3771 else if (!constant->expr()->is_constant())
3773 go_error_at(constant->expr()->location(), "expression is not constant");
3774 constant->set_error();
3776 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3777 NULL))
3779 go_error_at(constant->location(),
3780 "initialization expression has wrong type");
3781 constant->set_error();
3783 return TRAVERSE_CONTINUE;
3786 // There are no types to check in a function, but this is where we
3787 // issue warnings about labels which are defined but not referenced.
3790 Check_types_traverse::function(Named_object* no)
3792 no->func_value()->check_labels();
3793 return TRAVERSE_CONTINUE;
3796 // Check that types are valid in a statement.
3799 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3801 s->check_types(this->gogo_);
3802 return TRAVERSE_CONTINUE;
3805 // Check that types are valid in an expression.
3808 Check_types_traverse::expression(Expression** expr)
3810 (*expr)->check_types(this->gogo_);
3811 return TRAVERSE_CONTINUE;
3814 // Check that types are valid.
3816 void
3817 Gogo::check_types()
3819 Check_types_traverse traverse(this);
3820 this->traverse(&traverse);
3822 Bindings* bindings = this->current_bindings();
3823 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3824 p != bindings->end_declarations();
3825 ++p)
3827 // Also check the types in a function declaration's signature.
3828 Named_object* no = p->second;
3829 if (no->is_function_declaration())
3830 no->func_declaration_value()->check_types();
3834 // Check the types in a single block.
3836 void
3837 Gogo::check_types_in_block(Block* block)
3839 Check_types_traverse traverse(this);
3840 block->traverse(&traverse);
3843 // A traversal class which finds all the expressions which must be
3844 // evaluated in order within a statement or larger expression. This
3845 // is used to implement the rules about order of evaluation.
3847 class Find_eval_ordering : public Traverse
3849 private:
3850 typedef std::vector<Expression**> Expression_pointers;
3852 public:
3853 Find_eval_ordering()
3854 : Traverse(traverse_blocks
3855 | traverse_statements
3856 | traverse_expressions),
3857 exprs_()
3860 size_t
3861 size() const
3862 { return this->exprs_.size(); }
3864 typedef Expression_pointers::const_iterator const_iterator;
3866 const_iterator
3867 begin() const
3868 { return this->exprs_.begin(); }
3870 const_iterator
3871 end() const
3872 { return this->exprs_.end(); }
3874 protected:
3876 block(Block*)
3877 { return TRAVERSE_SKIP_COMPONENTS; }
3880 statement(Block*, size_t*, Statement*)
3881 { return TRAVERSE_SKIP_COMPONENTS; }
3884 expression(Expression**);
3886 private:
3887 // A list of pointers to expressions with side-effects.
3888 Expression_pointers exprs_;
3891 // If an expression must be evaluated in order, put it on the list.
3894 Find_eval_ordering::expression(Expression** expression_pointer)
3896 Binary_expression* binexp = (*expression_pointer)->binary_expression();
3897 if (binexp != NULL
3898 && (binexp->op() == OPERATOR_ANDAND || binexp->op() == OPERATOR_OROR))
3900 // Shortcut expressions may potentially have side effects which need
3901 // to be ordered, so add them to the list.
3902 // We don't order its subexpressions here since they may be evaluated
3903 // conditionally. This is handled in remove_shortcuts.
3904 this->exprs_.push_back(expression_pointer);
3905 return TRAVERSE_SKIP_COMPONENTS;
3908 // We have to look at subexpressions before this one.
3909 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3910 return TRAVERSE_EXIT;
3911 if ((*expression_pointer)->must_eval_in_order())
3912 this->exprs_.push_back(expression_pointer);
3913 return TRAVERSE_SKIP_COMPONENTS;
3916 // A traversal class for ordering evaluations.
3918 class Order_eval : public Traverse
3920 public:
3921 Order_eval(Gogo* gogo)
3922 : Traverse(traverse_variables
3923 | traverse_statements),
3924 gogo_(gogo)
3928 variable(Named_object*);
3931 statement(Block*, size_t*, Statement*);
3933 private:
3934 // The IR.
3935 Gogo* gogo_;
3938 // Implement the order of evaluation rules for a statement.
3941 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3943 // FIXME: This approach doesn't work for switch statements, because
3944 // we add the new statements before the whole switch when we need to
3945 // instead add them just before the switch expression. The right
3946 // fix is probably to lower switch statements with nonconstant cases
3947 // to a series of conditionals.
3948 if (stmt->switch_statement() != NULL)
3949 return TRAVERSE_CONTINUE;
3951 Find_eval_ordering find_eval_ordering;
3953 // If S is a variable declaration, then ordinary traversal won't do
3954 // anything. We want to explicitly traverse the initialization
3955 // expression if there is one.
3956 Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3957 Expression* init = NULL;
3958 Expression* orig_init = NULL;
3959 if (vds == NULL)
3960 stmt->traverse_contents(&find_eval_ordering);
3961 else
3963 init = vds->var()->var_value()->init();
3964 if (init == NULL)
3965 return TRAVERSE_CONTINUE;
3966 orig_init = init;
3968 // It might seem that this could be
3969 // init->traverse_subexpressions. Unfortunately that can fail
3970 // in a case like
3971 // var err os.Error
3972 // newvar, err := call(arg())
3973 // Here newvar will have an init of call result 0 of
3974 // call(arg()). If we only traverse subexpressions, we will
3975 // only find arg(), and we won't bother to move anything out.
3976 // Then we get to the assignment to err, we will traverse the
3977 // whole statement, and this time we will find both call() and
3978 // arg(), and so we will move them out. This will cause them to
3979 // be put into temporary variables before the assignment to err
3980 // but after the declaration of newvar. To avoid that problem,
3981 // we traverse the entire expression here.
3982 Expression::traverse(&init, &find_eval_ordering);
3985 size_t c = find_eval_ordering.size();
3986 if (c == 0)
3987 return TRAVERSE_CONTINUE;
3989 // If there is only one expression with a side-effect, we can
3990 // usually leave it in place.
3991 if (c == 1)
3993 switch (stmt->classification())
3995 case Statement::STATEMENT_ASSIGNMENT:
3996 // For an assignment statement, we need to evaluate an
3997 // expression on the right hand side before we evaluate any
3998 // index expression on the left hand side, so for that case
3999 // we always move the expression. Otherwise we mishandle
4000 // m[0] = len(m) where m is a map.
4001 break;
4003 case Statement::STATEMENT_EXPRESSION:
4005 // If this is a call statement that doesn't return any
4006 // values, it will not have been counted as a value to
4007 // move. We need to move any subexpressions in case they
4008 // are themselves call statements that require passing a
4009 // closure.
4010 Expression* expr = stmt->expression_statement()->expr();
4011 if (expr->call_expression() != NULL
4012 && expr->call_expression()->result_count() == 0)
4013 break;
4014 return TRAVERSE_CONTINUE;
4017 default:
4018 // We can leave the expression in place.
4019 return TRAVERSE_CONTINUE;
4023 bool is_thunk = stmt->thunk_statement() != NULL;
4024 Expression_statement* es = stmt->expression_statement();
4025 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
4026 p != find_eval_ordering.end();
4027 ++p)
4029 Expression** pexpr = *p;
4031 // The last expression in a thunk will be the call passed to go
4032 // or defer, which we must not evaluate early.
4033 if (is_thunk && p + 1 == find_eval_ordering.end())
4034 break;
4036 Location loc = (*pexpr)->location();
4037 Statement* s;
4038 if ((*pexpr)->call_expression() == NULL
4039 || (*pexpr)->call_expression()->result_count() < 2)
4041 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
4042 loc);
4043 s = ts;
4044 *pexpr = Expression::make_temporary_reference(ts, loc);
4046 else
4048 // A call expression which returns multiple results needs to
4049 // be handled specially. We can't create a temporary
4050 // because there is no type to give it. Any actual uses of
4051 // the values will be done via Call_result_expressions.
4053 // Since a given call expression can be shared by multiple
4054 // Call_result_expressions, avoid hoisting the call the
4055 // second time we see it here. In addition, don't try to
4056 // hoist the top-level multi-return call in the statement,
4057 // since doing this would result a tree with more than one copy
4058 // of the call.
4059 if (this->remember_expression(*pexpr))
4060 s = NULL;
4061 else if (es != NULL && *pexpr == es->expr())
4062 s = NULL;
4063 else
4064 s = Statement::make_statement(*pexpr, true);
4067 if (s != NULL)
4069 block->insert_statement_before(*pindex, s);
4070 ++*pindex;
4074 if (init != orig_init)
4075 vds->var()->var_value()->set_init(init);
4077 return TRAVERSE_CONTINUE;
4080 // Implement the order of evaluation rules for the initializer of a
4081 // global variable.
4084 Order_eval::variable(Named_object* no)
4086 if (no->is_result_variable())
4087 return TRAVERSE_CONTINUE;
4088 Variable* var = no->var_value();
4089 Expression* init = var->init();
4090 if (!var->is_global() || init == NULL)
4091 return TRAVERSE_CONTINUE;
4093 Find_eval_ordering find_eval_ordering;
4094 Expression::traverse(&init, &find_eval_ordering);
4096 if (find_eval_ordering.size() <= 1)
4098 // If there is only one expression with a side-effect, we can
4099 // leave it in place.
4100 return TRAVERSE_SKIP_COMPONENTS;
4103 Expression* orig_init = init;
4105 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
4106 p != find_eval_ordering.end();
4107 ++p)
4109 Expression** pexpr = *p;
4110 Location loc = (*pexpr)->location();
4111 Statement* s;
4112 if ((*pexpr)->call_expression() == NULL
4113 || (*pexpr)->call_expression()->result_count() < 2)
4115 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
4116 loc);
4117 s = ts;
4118 *pexpr = Expression::make_temporary_reference(ts, loc);
4120 else
4122 // A call expression which returns multiple results needs to
4123 // be handled specially.
4124 s = Statement::make_statement(*pexpr, true);
4126 var->add_preinit_statement(this->gogo_, s);
4129 if (init != orig_init)
4130 var->set_init(init);
4132 return TRAVERSE_SKIP_COMPONENTS;
4135 // Use temporary variables to implement the order of evaluation rules.
4137 void
4138 Gogo::order_evaluations()
4140 Order_eval order_eval(this);
4141 this->traverse(&order_eval);
4144 // Order evaluations in a block.
4146 void
4147 Gogo::order_block(Block* block)
4149 Order_eval order_eval(this);
4150 block->traverse(&order_eval);
4153 // A traversal class used to find a single shortcut operator within an
4154 // expression.
4156 class Find_shortcut : public Traverse
4158 public:
4159 Find_shortcut()
4160 : Traverse(traverse_blocks
4161 | traverse_statements
4162 | traverse_expressions),
4163 found_(NULL)
4166 // A pointer to the expression which was found, or NULL if none was
4167 // found.
4168 Expression**
4169 found() const
4170 { return this->found_; }
4172 protected:
4174 block(Block*)
4175 { return TRAVERSE_SKIP_COMPONENTS; }
4178 statement(Block*, size_t*, Statement*)
4179 { return TRAVERSE_SKIP_COMPONENTS; }
4182 expression(Expression**);
4184 private:
4185 Expression** found_;
4188 // Find a shortcut expression.
4191 Find_shortcut::expression(Expression** pexpr)
4193 Expression* expr = *pexpr;
4194 Binary_expression* be = expr->binary_expression();
4195 if (be == NULL)
4196 return TRAVERSE_CONTINUE;
4197 Operator op = be->op();
4198 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
4199 return TRAVERSE_CONTINUE;
4200 go_assert(this->found_ == NULL);
4201 this->found_ = pexpr;
4202 return TRAVERSE_EXIT;
4205 // A traversal class used to turn shortcut operators into explicit if
4206 // statements.
4208 class Shortcuts : public Traverse
4210 public:
4211 Shortcuts(Gogo* gogo)
4212 : Traverse(traverse_variables
4213 | traverse_statements),
4214 gogo_(gogo)
4217 protected:
4219 variable(Named_object*);
4222 statement(Block*, size_t*, Statement*);
4224 private:
4225 // Convert a shortcut operator.
4226 Statement*
4227 convert_shortcut(Block* enclosing, Expression** pshortcut);
4229 // The IR.
4230 Gogo* gogo_;
4233 // Remove shortcut operators in a single statement.
4236 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
4238 // FIXME: This approach doesn't work for switch statements, because
4239 // we add the new statements before the whole switch when we need to
4240 // instead add them just before the switch expression. The right
4241 // fix is probably to lower switch statements with nonconstant cases
4242 // to a series of conditionals.
4243 if (s->switch_statement() != NULL)
4244 return TRAVERSE_CONTINUE;
4246 while (true)
4248 Find_shortcut find_shortcut;
4250 // If S is a variable declaration, then ordinary traversal won't
4251 // do anything. We want to explicitly traverse the
4252 // initialization expression if there is one.
4253 Variable_declaration_statement* vds = s->variable_declaration_statement();
4254 Expression* init = NULL;
4255 if (vds == NULL)
4256 s->traverse_contents(&find_shortcut);
4257 else
4259 init = vds->var()->var_value()->init();
4260 if (init == NULL)
4261 return TRAVERSE_CONTINUE;
4262 init->traverse(&init, &find_shortcut);
4264 Expression** pshortcut = find_shortcut.found();
4265 if (pshortcut == NULL)
4266 return TRAVERSE_CONTINUE;
4268 Statement* snew = this->convert_shortcut(block, pshortcut);
4269 block->insert_statement_before(*pindex, snew);
4270 ++*pindex;
4272 if (pshortcut == &init)
4273 vds->var()->var_value()->set_init(init);
4277 // Remove shortcut operators in the initializer of a global variable.
4280 Shortcuts::variable(Named_object* no)
4282 if (no->is_result_variable())
4283 return TRAVERSE_CONTINUE;
4284 Variable* var = no->var_value();
4285 Expression* init = var->init();
4286 if (!var->is_global() || init == NULL)
4287 return TRAVERSE_CONTINUE;
4289 while (true)
4291 Find_shortcut find_shortcut;
4292 init->traverse(&init, &find_shortcut);
4293 Expression** pshortcut = find_shortcut.found();
4294 if (pshortcut == NULL)
4295 return TRAVERSE_CONTINUE;
4297 Statement* snew = this->convert_shortcut(NULL, pshortcut);
4298 var->add_preinit_statement(this->gogo_, snew);
4299 if (pshortcut == &init)
4300 var->set_init(init);
4304 // Given an expression which uses a shortcut operator, return a
4305 // statement which implements it, and update *PSHORTCUT accordingly.
4307 Statement*
4308 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
4310 Binary_expression* shortcut = (*pshortcut)->binary_expression();
4311 Expression* left = shortcut->left();
4312 Expression* right = shortcut->right();
4313 Location loc = shortcut->location();
4315 Block* retblock = new Block(enclosing, loc);
4316 retblock->set_end_location(loc);
4318 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
4319 left, loc);
4320 retblock->add_statement(ts);
4322 Block* block = new Block(retblock, loc);
4323 block->set_end_location(loc);
4324 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
4325 Statement* assign = Statement::make_assignment(tmpref, right, loc);
4326 block->add_statement(assign);
4328 Expression* cond = Expression::make_temporary_reference(ts, loc);
4329 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
4330 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
4332 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
4333 loc);
4334 retblock->add_statement(if_statement);
4336 *pshortcut = Expression::make_temporary_reference(ts, loc);
4338 delete shortcut;
4340 // Now convert any shortcut operators in LEFT and RIGHT.
4341 // LEFT and RIGHT were skipped in the top level
4342 // Gogo::order_evaluations. We need to order their
4343 // components first.
4344 Order_eval order_eval(this->gogo_);
4345 retblock->traverse(&order_eval);
4346 Shortcuts shortcuts(this->gogo_);
4347 retblock->traverse(&shortcuts);
4349 return Statement::make_block_statement(retblock, loc);
4352 // Turn shortcut operators into explicit if statements. Doing this
4353 // considerably simplifies the order of evaluation rules.
4355 void
4356 Gogo::remove_shortcuts()
4358 Shortcuts shortcuts(this);
4359 this->traverse(&shortcuts);
4362 // Turn shortcut operators into explicit if statements in a block.
4364 void
4365 Gogo::remove_shortcuts_in_block(Block* block)
4367 Shortcuts shortcuts(this);
4368 block->traverse(&shortcuts);
4371 // Traversal to flatten parse tree after order of evaluation rules are applied.
4373 class Flatten : public Traverse
4375 public:
4376 Flatten(Gogo* gogo, Named_object* function)
4377 : Traverse(traverse_variables
4378 | traverse_functions
4379 | traverse_statements
4380 | traverse_expressions),
4381 gogo_(gogo), function_(function), inserter_()
4384 void
4385 set_inserter(const Statement_inserter* inserter)
4386 { this->inserter_ = *inserter; }
4389 variable(Named_object*);
4392 function(Named_object*);
4395 statement(Block*, size_t* pindex, Statement*);
4398 expression(Expression**);
4400 private:
4401 // General IR.
4402 Gogo* gogo_;
4403 // The function we are traversing.
4404 Named_object* function_;
4405 // Current statement inserter for use by expressions.
4406 Statement_inserter inserter_;
4409 // Flatten variables.
4412 Flatten::variable(Named_object* no)
4414 if (!no->is_variable())
4415 return TRAVERSE_CONTINUE;
4417 if (no->is_variable() && no->var_value()->is_global())
4419 // Global variables can have loops in their initialization
4420 // expressions. This is handled in flatten_init_expression.
4421 no->var_value()->flatten_init_expression(this->gogo_, this->function_,
4422 &this->inserter_);
4423 return TRAVERSE_CONTINUE;
4426 if (!no->var_value()->is_parameter()
4427 && !no->var_value()->is_receiver()
4428 && !no->var_value()->is_closure()
4429 && no->var_value()->is_non_escaping_address_taken()
4430 && !no->var_value()->is_in_heap()
4431 && no->var_value()->toplevel_decl() == NULL)
4433 // Local variable that has address taken but not escape.
4434 // It needs to be live beyond its lexical scope. So we
4435 // create a top-level declaration for it.
4436 // No need to do it if it is already in the top level.
4437 Block* top_block = function_->func_value()->block();
4438 if (top_block->bindings()->lookup_local(no->name()) != no)
4440 Variable* var = no->var_value();
4441 Temporary_statement* ts =
4442 Statement::make_temporary(var->type(), NULL, var->location());
4443 ts->set_is_address_taken();
4444 top_block->add_statement_at_front(ts);
4445 var->set_toplevel_decl(ts);
4449 go_assert(!no->var_value()->has_pre_init());
4451 return TRAVERSE_SKIP_COMPONENTS;
4454 // Flatten the body of a function. Record the function while flattening it,
4455 // so that we can pass it down when flattening an expression.
4458 Flatten::function(Named_object* no)
4460 go_assert(this->function_ == NULL);
4461 this->function_ = no;
4462 int t = no->func_value()->traverse(this);
4463 this->function_ = NULL;
4465 if (t == TRAVERSE_EXIT)
4466 return t;
4467 return TRAVERSE_SKIP_COMPONENTS;
4470 // Flatten statement parse trees.
4473 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
4475 // Because we explicitly traverse the statement's contents
4476 // ourselves, we want to skip block statements here. There is
4477 // nothing to flatten in a block statement.
4478 if (sorig->is_block_statement())
4479 return TRAVERSE_CONTINUE;
4481 Statement_inserter hold_inserter(this->inserter_);
4482 this->inserter_ = Statement_inserter(block, pindex);
4484 // Flatten the expressions first.
4485 int t = sorig->traverse_contents(this);
4486 if (t == TRAVERSE_EXIT)
4488 this->inserter_ = hold_inserter;
4489 return t;
4492 // Keep flattening until nothing changes.
4493 Statement* s = sorig;
4494 while (true)
4496 Statement* snew = s->flatten(this->gogo_, this->function_, block,
4497 &this->inserter_);
4498 if (snew == s)
4499 break;
4500 s = snew;
4501 t = s->traverse_contents(this);
4502 if (t == TRAVERSE_EXIT)
4504 this->inserter_ = hold_inserter;
4505 return t;
4509 if (s != sorig)
4510 block->replace_statement(*pindex, s);
4512 this->inserter_ = hold_inserter;
4513 return TRAVERSE_SKIP_COMPONENTS;
4516 // Flatten expression parse trees.
4519 Flatten::expression(Expression** pexpr)
4521 // Keep flattening until nothing changes.
4522 while (true)
4524 Expression* e = *pexpr;
4525 if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
4526 return TRAVERSE_EXIT;
4528 Expression* enew = e->flatten(this->gogo_, this->function_,
4529 &this->inserter_);
4530 if (enew == e)
4531 break;
4532 *pexpr = enew;
4534 return TRAVERSE_SKIP_COMPONENTS;
4537 // Flatten a block.
4539 void
4540 Gogo::flatten_block(Named_object* function, Block* block)
4542 Flatten flatten(this, function);
4543 block->traverse(&flatten);
4546 // Flatten an expression. INSERTER may be NULL, in which case the
4547 // expression had better not need to create any temporaries.
4549 void
4550 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
4551 Expression** pexpr)
4553 Flatten flatten(this, function);
4554 if (inserter != NULL)
4555 flatten.set_inserter(inserter);
4556 flatten.expression(pexpr);
4559 void
4560 Gogo::flatten()
4562 Flatten flatten(this, NULL);
4563 this->traverse(&flatten);
4566 // Traversal to convert calls to the predeclared recover function to
4567 // pass in an argument indicating whether it can recover from a panic
4568 // or not.
4570 class Convert_recover : public Traverse
4572 public:
4573 Convert_recover(Named_object* arg)
4574 : Traverse(traverse_expressions),
4575 arg_(arg)
4578 protected:
4580 expression(Expression**);
4582 private:
4583 // The argument to pass to the function.
4584 Named_object* arg_;
4587 // Convert calls to recover.
4590 Convert_recover::expression(Expression** pp)
4592 Call_expression* ce = (*pp)->call_expression();
4593 if (ce != NULL && ce->is_recover_call())
4594 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4595 ce->location()));
4596 return TRAVERSE_CONTINUE;
4599 // Traversal for build_recover_thunks.
4601 class Build_recover_thunks : public Traverse
4603 public:
4604 Build_recover_thunks(Gogo* gogo)
4605 : Traverse(traverse_functions),
4606 gogo_(gogo)
4610 function(Named_object*);
4612 private:
4613 Expression*
4614 can_recover_arg(Location);
4616 // General IR.
4617 Gogo* gogo_;
4620 // If this function calls recover, turn it into a thunk.
4623 Build_recover_thunks::function(Named_object* orig_no)
4625 Function* orig_func = orig_no->func_value();
4626 if (!orig_func->calls_recover()
4627 || orig_func->is_recover_thunk()
4628 || orig_func->has_recover_thunk())
4629 return TRAVERSE_CONTINUE;
4631 Gogo* gogo = this->gogo_;
4632 Location location = orig_func->location();
4634 static int count;
4635 char buf[50];
4637 Function_type* orig_fntype = orig_func->type();
4638 Typed_identifier_list* new_params = new Typed_identifier_list();
4639 std::string receiver_name;
4640 if (orig_fntype->is_method())
4642 const Typed_identifier* receiver = orig_fntype->receiver();
4643 snprintf(buf, sizeof buf, "rt.%u", count);
4644 ++count;
4645 receiver_name = buf;
4646 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4647 receiver->location()));
4649 const Typed_identifier_list* orig_params = orig_fntype->parameters();
4650 if (orig_params != NULL && !orig_params->empty())
4652 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4653 p != orig_params->end();
4654 ++p)
4656 snprintf(buf, sizeof buf, "pt.%u", count);
4657 ++count;
4658 new_params->push_back(Typed_identifier(buf, p->type(),
4659 p->location()));
4662 snprintf(buf, sizeof buf, "pr.%u", count);
4663 ++count;
4664 std::string can_recover_name = buf;
4665 new_params->push_back(Typed_identifier(can_recover_name,
4666 Type::lookup_bool_type(),
4667 orig_fntype->location()));
4669 const Typed_identifier_list* orig_results = orig_fntype->results();
4670 Typed_identifier_list* new_results;
4671 if (orig_results == NULL || orig_results->empty())
4672 new_results = NULL;
4673 else
4675 new_results = new Typed_identifier_list();
4676 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4677 p != orig_results->end();
4678 ++p)
4679 new_results->push_back(Typed_identifier("", p->type(), p->location()));
4682 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4683 new_results,
4684 orig_fntype->location());
4685 if (orig_fntype->is_varargs())
4686 new_fntype->set_is_varargs();
4688 Type* rtype = NULL;
4689 if (orig_fntype->is_method())
4690 rtype = orig_fntype->receiver()->type();
4691 std::string name(gogo->recover_thunk_name(orig_no->name(), rtype));
4692 Named_object *new_no = gogo->start_function(name, new_fntype, false,
4693 location);
4694 Function *new_func = new_no->func_value();
4695 if (orig_func->enclosing() != NULL)
4696 new_func->set_enclosing(orig_func->enclosing());
4698 // We build the code for the original function attached to the new
4699 // function, and then swap the original and new function bodies.
4700 // This means that existing references to the original function will
4701 // then refer to the new function. That makes this code a little
4702 // confusing, in that the reference to NEW_NO really refers to the
4703 // other function, not the one we are building.
4705 Expression* closure = NULL;
4706 if (orig_func->needs_closure())
4708 // For the new function we are creating, declare a new parameter
4709 // variable NEW_CLOSURE_NO and set it to be the closure variable
4710 // of the function. This will be set to the closure value
4711 // passed in by the caller. Then pass a reference to this
4712 // variable as the closure value when calling the original
4713 // function. In other words, simply pass the closure value
4714 // through the thunk we are creating.
4715 Named_object* orig_closure_no = orig_func->closure_var();
4716 Variable* orig_closure_var = orig_closure_no->var_value();
4717 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4718 false, false, location);
4719 new_var->set_is_closure();
4720 snprintf(buf, sizeof buf, "closure.%u", count);
4721 ++count;
4722 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4723 new_var);
4724 new_func->set_closure_var(new_closure_no);
4725 closure = Expression::make_var_reference(new_closure_no, location);
4728 Expression* fn = Expression::make_func_reference(new_no, closure, location);
4730 Expression_list* args = new Expression_list();
4731 if (new_params != NULL)
4733 // Note that we skip the last parameter, which is the boolean
4734 // indicating whether recover can succed.
4735 for (Typed_identifier_list::const_iterator p = new_params->begin();
4736 p + 1 != new_params->end();
4737 ++p)
4739 Named_object* p_no = gogo->lookup(p->name(), NULL);
4740 go_assert(p_no != NULL
4741 && p_no->is_variable()
4742 && p_no->var_value()->is_parameter());
4743 args->push_back(Expression::make_var_reference(p_no, location));
4746 args->push_back(this->can_recover_arg(location));
4748 gogo->start_block(location);
4750 Call_expression* call = Expression::make_call(fn, args, false, location);
4752 // Any varargs call has already been lowered.
4753 call->set_varargs_are_lowered();
4755 Statement* s = Statement::make_return_from_call(call, location);
4756 s->determine_types();
4757 gogo->add_statement(s);
4759 Block* b = gogo->finish_block(location);
4761 gogo->add_block(b, location);
4763 // Lower the call in case it returns multiple results.
4764 gogo->lower_block(new_no, b);
4766 gogo->finish_function(location);
4768 // Swap the function bodies and types.
4769 new_func->swap_for_recover(orig_func);
4770 orig_func->set_is_recover_thunk();
4771 new_func->set_calls_recover();
4772 new_func->set_has_recover_thunk();
4774 Bindings* orig_bindings = orig_func->block()->bindings();
4775 Bindings* new_bindings = new_func->block()->bindings();
4776 if (orig_fntype->is_method())
4778 // We changed the receiver to be a regular parameter. We have
4779 // to update the binding accordingly in both functions.
4780 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4781 go_assert(orig_rec_no != NULL
4782 && orig_rec_no->is_variable()
4783 && !orig_rec_no->var_value()->is_receiver());
4784 orig_rec_no->var_value()->set_is_receiver();
4786 std::string new_receiver_name(orig_fntype->receiver()->name());
4787 if (new_receiver_name.empty())
4789 // Find the receiver. It was named "r.NNN" in
4790 // Gogo::start_function.
4791 for (Bindings::const_definitions_iterator p =
4792 new_bindings->begin_definitions();
4793 p != new_bindings->end_definitions();
4794 ++p)
4796 const std::string& pname((*p)->name());
4797 if (pname[0] == 'r' && pname[1] == '.')
4799 new_receiver_name = pname;
4800 break;
4803 go_assert(!new_receiver_name.empty());
4805 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4806 if (new_rec_no == NULL)
4807 go_assert(saw_errors());
4808 else
4810 go_assert(new_rec_no->is_variable()
4811 && new_rec_no->var_value()->is_receiver());
4812 new_rec_no->var_value()->set_is_not_receiver();
4816 // Because we flipped blocks but not types, the can_recover
4817 // parameter appears in the (now) old bindings as a parameter.
4818 // Change it to a local variable, whereupon it will be discarded.
4819 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4820 go_assert(can_recover_no != NULL
4821 && can_recover_no->is_variable()
4822 && can_recover_no->var_value()->is_parameter());
4823 orig_bindings->remove_binding(can_recover_no);
4825 // Add the can_recover argument to the (now) new bindings, and
4826 // attach it to any recover statements.
4827 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4828 false, true, false, location);
4829 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4830 can_recover_var);
4831 Convert_recover convert_recover(can_recover_no);
4832 new_func->traverse(&convert_recover);
4834 // Update the function pointers in any named results.
4835 new_func->update_result_variables();
4836 orig_func->update_result_variables();
4838 return TRAVERSE_CONTINUE;
4841 // Return the expression to pass for the .can_recover parameter to the
4842 // new function. This indicates whether a call to recover may return
4843 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4845 Expression*
4846 Build_recover_thunks::can_recover_arg(Location location)
4848 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4849 static Named_object* can_recover;
4850 if (can_recover == NULL)
4852 const Location bloc = Linemap::predeclared_location();
4853 Typed_identifier_list* param_types = new Typed_identifier_list();
4854 param_types->push_back(Typed_identifier("a", uintptr_type, bloc));
4855 Type* boolean_type = Type::lookup_bool_type();
4856 Typed_identifier_list* results = new Typed_identifier_list();
4857 results->push_back(Typed_identifier("", boolean_type, bloc));
4858 Function_type* fntype = Type::make_function_type(NULL, param_types,
4859 results, bloc);
4860 can_recover =
4861 Named_object::make_function_declaration("runtime_canrecover",
4862 NULL, fntype, bloc);
4863 can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4866 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4867 Expression* call = Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS,
4868 location, 1, zexpr);
4869 call = Expression::make_unsafe_cast(uintptr_type, call, location);
4871 Expression_list* args = new Expression_list();
4872 args->push_back(call);
4874 Expression* fn = Expression::make_func_reference(can_recover, NULL, location);
4875 return Expression::make_call(fn, args, false, location);
4878 // Build thunks for functions which call recover. We build a new
4879 // function with an extra parameter, which is whether a call to
4880 // recover can succeed. We then move the body of this function to
4881 // that one. We then turn this function into a thunk which calls the
4882 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4883 // The function will be marked as not splitting the stack. This will
4884 // cooperate with the implementation of defer to make recover do the
4885 // right thing.
4887 void
4888 Gogo::build_recover_thunks()
4890 Build_recover_thunks build_recover_thunks(this);
4891 this->traverse(&build_recover_thunks);
4894 // Look for named types to see whether we need to create an interface
4895 // method table.
4897 class Build_method_tables : public Traverse
4899 public:
4900 Build_method_tables(Gogo* gogo,
4901 const std::vector<Interface_type*>& interfaces)
4902 : Traverse(traverse_types),
4903 gogo_(gogo), interfaces_(interfaces)
4907 type(Type*);
4909 private:
4910 // The IR.
4911 Gogo* gogo_;
4912 // A list of locally defined interfaces which have hidden methods.
4913 const std::vector<Interface_type*>& interfaces_;
4916 // Build all required interface method tables for types. We need to
4917 // ensure that we have an interface method table for every interface
4918 // which has a hidden method, for every named type which implements
4919 // that interface. Normally we can just build interface method tables
4920 // as we need them. However, in some cases we can require an
4921 // interface method table for an interface defined in a different
4922 // package for a type defined in that package. If that interface and
4923 // type both use a hidden method, that is OK. However, we will not be
4924 // able to build that interface method table when we need it, because
4925 // the type's hidden method will be static. So we have to build it
4926 // here, and just refer it from other packages as needed.
4928 void
4929 Gogo::build_interface_method_tables()
4931 if (saw_errors())
4932 return;
4934 std::vector<Interface_type*> hidden_interfaces;
4935 hidden_interfaces.reserve(this->interface_types_.size());
4936 for (std::vector<Interface_type*>::const_iterator pi =
4937 this->interface_types_.begin();
4938 pi != this->interface_types_.end();
4939 ++pi)
4941 const Typed_identifier_list* methods = (*pi)->methods();
4942 if (methods == NULL)
4943 continue;
4944 for (Typed_identifier_list::const_iterator pm = methods->begin();
4945 pm != methods->end();
4946 ++pm)
4948 if (Gogo::is_hidden_name(pm->name()))
4950 hidden_interfaces.push_back(*pi);
4951 break;
4956 if (!hidden_interfaces.empty())
4958 // Now traverse the tree looking for all named types.
4959 Build_method_tables bmt(this, hidden_interfaces);
4960 this->traverse(&bmt);
4963 // We no longer need the list of interfaces.
4965 this->interface_types_.clear();
4968 // This is called for each type. For a named type, for each of the
4969 // interfaces with hidden methods that it implements, create the
4970 // method table.
4973 Build_method_tables::type(Type* type)
4975 Named_type* nt = type->named_type();
4976 Struct_type* st = type->struct_type();
4977 if (nt != NULL || st != NULL)
4979 Translate_context context(this->gogo_, NULL, NULL, NULL);
4980 for (std::vector<Interface_type*>::const_iterator p =
4981 this->interfaces_.begin();
4982 p != this->interfaces_.end();
4983 ++p)
4985 // We ask whether a pointer to the named type implements the
4986 // interface, because a pointer can implement more methods
4987 // than a value.
4988 if (nt != NULL)
4990 if ((*p)->implements_interface(Type::make_pointer_type(nt),
4991 NULL))
4993 nt->interface_method_table(*p, false)->get_backend(&context);
4994 nt->interface_method_table(*p, true)->get_backend(&context);
4997 else
4999 if ((*p)->implements_interface(Type::make_pointer_type(st),
5000 NULL))
5002 st->interface_method_table(*p, false)->get_backend(&context);
5003 st->interface_method_table(*p, true)->get_backend(&context);
5008 return TRAVERSE_CONTINUE;
5011 // Return an expression which allocates memory to hold values of type TYPE.
5013 Expression*
5014 Gogo::allocate_memory(Type* type, Location location)
5016 Expression* td = Expression::make_type_descriptor(type, location);
5017 return Runtime::make_call(Runtime::NEW, location, 1, td);
5020 // Traversal class used to check for return statements.
5022 class Check_return_statements_traverse : public Traverse
5024 public:
5025 Check_return_statements_traverse()
5026 : Traverse(traverse_functions)
5030 function(Named_object*);
5033 // Check that a function has a return statement if it needs one.
5036 Check_return_statements_traverse::function(Named_object* no)
5038 Function* func = no->func_value();
5039 const Function_type* fntype = func->type();
5040 const Typed_identifier_list* results = fntype->results();
5042 // We only need a return statement if there is a return value.
5043 if (results == NULL || results->empty())
5044 return TRAVERSE_CONTINUE;
5046 if (func->block()->may_fall_through())
5047 go_error_at(func->block()->end_location(),
5048 "missing return at end of function");
5050 return TRAVERSE_CONTINUE;
5053 // Check return statements.
5055 void
5056 Gogo::check_return_statements()
5058 Check_return_statements_traverse traverse;
5059 this->traverse(&traverse);
5062 // Traversal class to decide whether a function body is less than the
5063 // inlining budget. This adjusts *available as it goes, and stops the
5064 // traversal if it goes negative.
5066 class Inline_within_budget : public Traverse
5068 public:
5069 Inline_within_budget(int* available)
5070 : Traverse(traverse_statements
5071 | traverse_expressions),
5072 available_(available)
5076 statement(Block*, size_t*, Statement*);
5079 expression(Expression**);
5081 private:
5082 // Pointer to remaining budget.
5083 int* available_;
5086 // Adjust the budget for the inlining cost of a statement.
5089 Inline_within_budget::statement(Block*, size_t*, Statement* s)
5091 if (*this->available_ < 0)
5092 return TRAVERSE_EXIT;
5093 *this->available_ -= s->inlining_cost();
5094 return TRAVERSE_CONTINUE;
5097 // Adjust the budget for the inlining cost of an expression.
5100 Inline_within_budget::expression(Expression** pexpr)
5102 if (*this->available_ < 0)
5103 return TRAVERSE_EXIT;
5104 *this->available_ -= (*pexpr)->inlining_cost();
5105 return TRAVERSE_CONTINUE;
5108 // Traversal class to find functions whose body should be exported for
5109 // inlining by other packages.
5111 class Mark_inline_candidates : public Traverse
5113 public:
5114 Mark_inline_candidates(Unordered_set(Named_object*)* marked)
5115 : Traverse(traverse_functions
5116 | traverse_types),
5117 marked_functions_(marked)
5121 function(Named_object*);
5124 type(Type*);
5126 private:
5127 // We traverse the function body trying to determine how expensive
5128 // it is for inlining. We start with a budget, and decrease that
5129 // budget for each statement and expression. If the budget goes
5130 // negative, we do not export the function body. The value of this
5131 // budget is a heuristic. In the usual GCC spirit, we could
5132 // consider setting this via a command line option.
5133 const int budget_heuristic = 80;
5135 // Set of named objects that are marked as inline candidates.
5136 Unordered_set(Named_object*)* marked_functions_;
5139 // Mark a function if it is an inline candidate.
5142 Mark_inline_candidates::function(Named_object* no)
5144 Function* func = no->func_value();
5145 if ((func->pragmas() & GOPRAGMA_NOINLINE) != 0)
5146 return TRAVERSE_CONTINUE;
5147 int budget = budget_heuristic;
5148 Inline_within_budget iwb(&budget);
5149 func->block()->traverse(&iwb);
5150 if (budget >= 0)
5152 func->set_export_for_inlining();
5153 this->marked_functions_->insert(no);
5155 return TRAVERSE_CONTINUE;
5158 // Mark methods if they are inline candidates.
5161 Mark_inline_candidates::type(Type* t)
5163 Named_type* nt = t->named_type();
5164 if (nt == NULL || nt->is_alias())
5165 return TRAVERSE_CONTINUE;
5166 const Bindings* methods = nt->local_methods();
5167 if (methods == NULL)
5168 return TRAVERSE_CONTINUE;
5169 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
5170 p != methods->end_definitions();
5171 ++p)
5173 Named_object* no = *p;
5174 go_assert(no->is_function());
5175 Function *func = no->func_value();
5176 if ((func->pragmas() & GOPRAGMA_NOINLINE) != 0)
5177 continue;
5178 int budget = budget_heuristic;
5179 Inline_within_budget iwb(&budget);
5180 func->block()->traverse(&iwb);
5181 if (budget >= 0)
5183 func->set_export_for_inlining();
5184 this->marked_functions_->insert(no);
5187 return TRAVERSE_CONTINUE;
5190 // Export identifiers as requested.
5192 void
5193 Gogo::do_exports()
5195 if (saw_errors())
5196 return;
5198 // Mark any functions whose body should be exported for inlining by
5199 // other packages.
5200 Unordered_set(Named_object*) marked_functions;
5201 Mark_inline_candidates mic(&marked_functions);
5202 this->traverse(&mic);
5204 // For now we always stream to a section. Later we may want to
5205 // support streaming to a separate file.
5206 Stream_to_section stream(this->backend());
5208 // Write out either the prefix or pkgpath depending on how we were
5209 // invoked.
5210 std::string prefix;
5211 std::string pkgpath;
5212 if (this->pkgpath_from_option_)
5213 pkgpath = this->pkgpath_;
5214 else if (this->prefix_from_option_)
5215 prefix = this->prefix_;
5216 else if (this->is_main_package())
5217 pkgpath = "main";
5218 else
5219 prefix = "go";
5221 std::string init_fn_name;
5222 if (this->is_main_package())
5223 init_fn_name = "";
5224 else if (this->need_init_fn_)
5225 init_fn_name = this->get_init_fn_name();
5226 else
5227 init_fn_name = this->dummy_init_fn_name();
5229 Export exp(&stream);
5230 exp.register_builtin_types(this);
5231 exp.export_globals(this->package_name(),
5232 prefix,
5233 pkgpath,
5234 this->packages_,
5235 this->imports_,
5236 init_fn_name,
5237 this->imported_init_fns_,
5238 this->package_->bindings(),
5239 &marked_functions);
5241 if (!this->c_header_.empty() && !saw_errors())
5242 this->write_c_header();
5245 // Write the top level named struct types in C format to a C header
5246 // file. This is used when building the runtime package, to share
5247 // struct definitions between C and Go.
5249 void
5250 Gogo::write_c_header()
5252 std::ofstream out;
5253 out.open(this->c_header_.c_str());
5254 if (out.fail())
5256 go_error_at(Linemap::unknown_location(),
5257 "cannot open %s: %m", this->c_header_.c_str());
5258 return;
5261 std::list<Named_object*> types;
5262 Bindings* top = this->package_->bindings();
5263 for (Bindings::const_definitions_iterator p = top->begin_definitions();
5264 p != top->end_definitions();
5265 ++p)
5267 Named_object* no = *p;
5269 // Skip names that start with underscore followed by something
5270 // other than an uppercase letter, as when compiling the runtime
5271 // package they are mostly types defined by mkrsysinfo.sh based
5272 // on the C system header files. We don't need to translate
5273 // types to C and back to Go. But do accept the special cases
5274 // _defer, _panic, and _type.
5275 std::string name = Gogo::unpack_hidden_name(no->name());
5276 if (name[0] == '_'
5277 && (name[1] < 'A' || name[1] > 'Z')
5278 && (name != "_defer" && name != "_panic" && name != "_type"))
5279 continue;
5281 if (no->is_type() && no->type_value()->struct_type() != NULL)
5282 types.push_back(no);
5283 if (no->is_const()
5284 && no->const_value()->type()->integer_type() != NULL
5285 && !no->const_value()->is_sink())
5287 Numeric_constant nc;
5288 unsigned long val;
5289 if (no->const_value()->expr()->numeric_constant_value(&nc)
5290 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
5292 out << "#define " << no->message_name() << ' ' << val
5293 << std::endl;
5298 std::vector<const Named_object*> written;
5299 int loop = 0;
5300 while (!types.empty())
5302 Named_object* no = types.front();
5303 types.pop_front();
5305 std::vector<const Named_object*> requires;
5306 std::vector<const Named_object*> declare;
5307 if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
5308 &declare))
5309 continue;
5311 bool ok = true;
5312 for (std::vector<const Named_object*>::const_iterator pr
5313 = requires.begin();
5314 pr != requires.end() && ok;
5315 ++pr)
5317 for (std::list<Named_object*>::const_iterator pt = types.begin();
5318 pt != types.end() && ok;
5319 ++pt)
5320 if (*pr == *pt)
5321 ok = false;
5323 if (!ok)
5325 ++loop;
5326 if (loop > 10000)
5328 // This should be impossible since the code parsed and
5329 // type checked.
5330 go_unreachable();
5333 types.push_back(no);
5334 continue;
5337 for (std::vector<const Named_object*>::const_iterator pd
5338 = declare.begin();
5339 pd != declare.end();
5340 ++pd)
5342 if (*pd == no)
5343 continue;
5345 std::vector<const Named_object*> drequires;
5346 std::vector<const Named_object*> ddeclare;
5347 if (!(*pd)->type_value()->struct_type()->
5348 can_write_to_c_header(&drequires, &ddeclare))
5349 continue;
5351 bool done = false;
5352 for (std::vector<const Named_object*>::const_iterator pw
5353 = written.begin();
5354 pw != written.end();
5355 ++pw)
5357 if (*pw == *pd)
5359 done = true;
5360 break;
5363 if (!done)
5365 out << std::endl;
5366 out << "struct " << (*pd)->message_name() << ";" << std::endl;
5367 written.push_back(*pd);
5371 out << std::endl;
5372 out << "struct " << no->message_name() << " {" << std::endl;
5373 no->type_value()->struct_type()->write_to_c_header(out);
5374 out << "};" << std::endl;
5375 written.push_back(no);
5378 out.close();
5379 if (out.fail())
5380 go_error_at(Linemap::unknown_location(),
5381 "error writing to %s: %m", this->c_header_.c_str());
5384 // Find the blocks in order to convert named types defined in blocks.
5386 class Convert_named_types : public Traverse
5388 public:
5389 Convert_named_types(Gogo* gogo)
5390 : Traverse(traverse_blocks),
5391 gogo_(gogo)
5394 protected:
5396 block(Block* block);
5398 private:
5399 Gogo* gogo_;
5403 Convert_named_types::block(Block* block)
5405 this->gogo_->convert_named_types_in_bindings(block->bindings());
5406 return TRAVERSE_CONTINUE;
5409 // Convert all named types to the backend representation. Since named
5410 // types can refer to other types, this needs to be done in the right
5411 // sequence, which is handled by Named_type::convert. Here we arrange
5412 // to call that for each named type.
5414 void
5415 Gogo::convert_named_types()
5417 this->convert_named_types_in_bindings(this->globals_);
5418 for (Packages::iterator p = this->packages_.begin();
5419 p != this->packages_.end();
5420 ++p)
5422 Package* package = p->second;
5423 this->convert_named_types_in_bindings(package->bindings());
5426 Convert_named_types cnt(this);
5427 this->traverse(&cnt);
5429 // Make all the builtin named types used for type descriptors, and
5430 // then convert them. They will only be written out if they are
5431 // needed.
5432 Type::make_type_descriptor_type();
5433 Type::make_type_descriptor_ptr_type();
5434 Function_type::make_function_type_descriptor_type();
5435 Pointer_type::make_pointer_type_descriptor_type();
5436 Struct_type::make_struct_type_descriptor_type();
5437 Array_type::make_array_type_descriptor_type();
5438 Array_type::make_slice_type_descriptor_type();
5439 Map_type::make_map_type_descriptor_type();
5440 Channel_type::make_chan_type_descriptor_type();
5441 Interface_type::make_interface_type_descriptor_type();
5442 Expression::make_func_descriptor_type();
5443 Type::convert_builtin_named_types(this);
5445 Runtime::convert_types(this);
5447 this->named_types_are_converted_ = true;
5449 Type::finish_pointer_types(this);
5452 // Convert all names types in a set of bindings.
5454 void
5455 Gogo::convert_named_types_in_bindings(Bindings* bindings)
5457 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5458 p != bindings->end_definitions();
5459 ++p)
5461 if ((*p)->is_type())
5462 (*p)->type_value()->convert(this);
5466 void
5467 debug_go_gogo(Gogo* gogo)
5469 if (gogo != NULL)
5470 gogo->debug_dump();
5473 void
5474 Gogo::debug_dump()
5476 std::cerr << "Packages:\n";
5477 for (Packages::const_iterator p = this->packages_.begin();
5478 p != this->packages_.end();
5479 ++p)
5481 const char *tag = " ";
5482 if (p->second == this->package_)
5483 tag = "* ";
5484 std::cerr << tag << "'" << p->first << "' "
5485 << p->second->pkgpath() << " " << ((void*)p->second) << "\n";
5489 // Class Function.
5491 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
5492 Location location)
5493 : type_(type), enclosing_(enclosing), results_(NULL),
5494 closure_var_(NULL), block_(block), location_(location), labels_(),
5495 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
5496 pragmas_(0), nested_functions_(0), is_sink_(false),
5497 results_are_named_(false), is_unnamed_type_stub_method_(false),
5498 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5499 calls_defer_retaddr_(false), is_type_specific_function_(false),
5500 in_unique_section_(false), export_for_inlining_(false),
5501 is_inline_only_(false), is_referenced_by_inline_(false),
5502 is_exported_by_linkname_(false)
5506 // Create the named result variables.
5508 void
5509 Function::create_result_variables(Gogo* gogo)
5511 const Typed_identifier_list* results = this->type_->results();
5512 if (results == NULL || results->empty())
5513 return;
5515 if (!results->front().name().empty())
5516 this->results_are_named_ = true;
5518 this->results_ = new Results();
5519 this->results_->reserve(results->size());
5521 Block* block = this->block_;
5522 int index = 0;
5523 for (Typed_identifier_list::const_iterator p = results->begin();
5524 p != results->end();
5525 ++p, ++index)
5527 std::string name = p->name();
5528 if (name.empty() || Gogo::is_sink_name(name))
5530 static int result_counter;
5531 char buf[100];
5532 snprintf(buf, sizeof buf, "$ret%d", result_counter);
5533 ++result_counter;
5534 name = gogo->pack_hidden_name(buf, false);
5536 Result_variable* result = new Result_variable(p->type(), this, index,
5537 p->location());
5538 Named_object* no = block->bindings()->add_result_variable(name, result);
5539 if (no->is_result_variable())
5540 this->results_->push_back(no);
5541 else
5543 static int dummy_result_count;
5544 char buf[100];
5545 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
5546 ++dummy_result_count;
5547 name = gogo->pack_hidden_name(buf, false);
5548 no = block->bindings()->add_result_variable(name, result);
5549 go_assert(no->is_result_variable());
5550 this->results_->push_back(no);
5555 // Update the named result variables when cloning a function which
5556 // calls recover.
5558 void
5559 Function::update_result_variables()
5561 if (this->results_ == NULL)
5562 return;
5564 for (Results::iterator p = this->results_->begin();
5565 p != this->results_->end();
5566 ++p)
5567 (*p)->result_var_value()->set_function(this);
5570 // Whether this method should not be included in the type descriptor.
5572 bool
5573 Function::nointerface() const
5575 go_assert(this->is_method());
5576 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
5579 // Record that this method should not be included in the type
5580 // descriptor.
5582 void
5583 Function::set_nointerface()
5585 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
5588 // Return the closure variable, creating it if necessary.
5590 Named_object*
5591 Function::closure_var()
5593 if (this->closure_var_ == NULL)
5595 go_assert(this->descriptor_ == NULL);
5596 // We don't know the type of the variable yet. We add fields as
5597 // we find them.
5598 Location loc = this->type_->location();
5599 Struct_field_list* sfl = new Struct_field_list;
5600 Struct_type* struct_type = Type::make_struct_type(sfl, loc);
5601 struct_type->set_is_struct_incomparable();
5602 Variable* var = new Variable(Type::make_pointer_type(struct_type),
5603 NULL, false, false, false, loc);
5604 var->set_is_used();
5605 var->set_is_closure();
5606 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
5607 // Note that the new variable is not in any binding contour.
5609 return this->closure_var_;
5612 // Set the type of the closure variable.
5614 void
5615 Function::set_closure_type()
5617 if (this->closure_var_ == NULL)
5618 return;
5619 Named_object* closure = this->closure_var_;
5620 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
5622 // The first field of a closure is always a pointer to the function
5623 // code.
5624 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
5625 st->push_field(Struct_field(Typed_identifier(".f", voidptr_type,
5626 this->location_)));
5628 unsigned int index = 1;
5629 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
5630 p != this->closure_fields_.end();
5631 ++p, ++index)
5633 Named_object* no = p->first;
5634 char buf[20];
5635 snprintf(buf, sizeof buf, "%u", index);
5636 std::string n = no->name() + buf;
5637 Type* var_type;
5638 if (no->is_variable())
5639 var_type = no->var_value()->type();
5640 else
5641 var_type = no->result_var_value()->type();
5642 Type* field_type = Type::make_pointer_type(var_type);
5643 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
5647 // Return whether this function is a method.
5649 bool
5650 Function::is_method() const
5652 return this->type_->is_method();
5655 // Add a label definition.
5657 Label*
5658 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
5659 Location location)
5661 Label* lnull = NULL;
5662 std::pair<Labels::iterator, bool> ins =
5663 this->labels_.insert(std::make_pair(label_name, lnull));
5664 Label* label;
5665 if (label_name == "_")
5667 label = Label::create_dummy_label();
5668 if (ins.second)
5669 ins.first->second = label;
5671 else if (ins.second)
5673 // This is a new label.
5674 label = new Label(label_name);
5675 ins.first->second = label;
5677 else
5679 // The label was already in the hash table.
5680 label = ins.first->second;
5681 if (label->is_defined())
5683 go_error_at(location, "label %qs already defined",
5684 Gogo::message_name(label_name).c_str());
5685 go_inform(label->location(), "previous definition of %qs was here",
5686 Gogo::message_name(label_name).c_str());
5687 return new Label(label_name);
5691 label->define(location, gogo->bindings_snapshot(location));
5693 // Issue any errors appropriate for any previous goto's to this
5694 // label.
5695 const std::vector<Bindings_snapshot*>& refs(label->refs());
5696 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
5697 p != refs.end();
5698 ++p)
5699 (*p)->check_goto_to(gogo->current_block());
5700 label->clear_refs();
5702 return label;
5705 // Add a reference to a label.
5707 Label*
5708 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5709 Location location, bool issue_goto_errors)
5711 Label* lnull = NULL;
5712 std::pair<Labels::iterator, bool> ins =
5713 this->labels_.insert(std::make_pair(label_name, lnull));
5714 Label* label;
5715 if (!ins.second)
5717 // The label was already in the hash table.
5718 label = ins.first->second;
5720 else
5722 go_assert(ins.first->second == NULL);
5723 label = new Label(label_name);
5724 ins.first->second = label;
5727 label->set_is_used();
5729 if (issue_goto_errors)
5731 Bindings_snapshot* snapshot = label->snapshot();
5732 if (snapshot != NULL)
5733 snapshot->check_goto_from(gogo->current_block(), location);
5734 else
5735 label->add_snapshot_ref(gogo->bindings_snapshot(location));
5738 return label;
5741 // Warn about labels that are defined but not used.
5743 void
5744 Function::check_labels() const
5746 for (Labels::const_iterator p = this->labels_.begin();
5747 p != this->labels_.end();
5748 p++)
5750 Label* label = p->second;
5751 if (!label->is_used())
5752 go_error_at(label->location(), "label %qs defined and not used",
5753 Gogo::message_name(label->name()).c_str());
5757 // Set the receiver type. This is used to remove aliases.
5759 void
5760 Function::set_receiver_type(Type* rtype)
5762 Function_type* oft = this->type_;
5763 Typed_identifier* rec = new Typed_identifier(oft->receiver()->name(),
5764 rtype,
5765 oft->receiver()->location());
5766 Typed_identifier_list* parameters = NULL;
5767 if (oft->parameters() != NULL)
5768 parameters = oft->parameters()->copy();
5769 Typed_identifier_list* results = NULL;
5770 if (oft->results() != NULL)
5771 results = oft->results()->copy();
5772 Function_type* nft = Type::make_function_type(rec, parameters, results,
5773 oft->location());
5774 this->type_ = nft;
5777 // Swap one function with another. This is used when building the
5778 // thunk we use to call a function which calls recover. It may not
5779 // work for any other case.
5781 void
5782 Function::swap_for_recover(Function *x)
5784 go_assert(this->enclosing_ == x->enclosing_);
5785 std::swap(this->results_, x->results_);
5786 std::swap(this->closure_var_, x->closure_var_);
5787 std::swap(this->block_, x->block_);
5788 go_assert(this->location_ == x->location_);
5789 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5790 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5793 // Traverse the tree.
5796 Function::traverse(Traverse* traverse)
5798 unsigned int traverse_mask = traverse->traverse_mask();
5800 if ((traverse_mask
5801 & (Traverse::traverse_types | Traverse::traverse_expressions))
5802 != 0)
5804 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5805 return TRAVERSE_EXIT;
5808 // FIXME: We should check traverse_functions here if nested
5809 // functions are stored in block bindings.
5810 if (this->block_ != NULL
5811 && (traverse_mask
5812 & (Traverse::traverse_variables
5813 | Traverse::traverse_constants
5814 | Traverse::traverse_blocks
5815 | Traverse::traverse_statements
5816 | Traverse::traverse_expressions
5817 | Traverse::traverse_types)) != 0)
5819 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5820 return TRAVERSE_EXIT;
5823 return TRAVERSE_CONTINUE;
5826 // Work out types for unspecified variables and constants.
5828 void
5829 Function::determine_types()
5831 if (this->block_ != NULL)
5832 this->block_->determine_types();
5835 // Return the function descriptor, the value you get when you refer to
5836 // the function in Go code without calling it.
5838 Expression*
5839 Function::descriptor(Gogo*, Named_object* no)
5841 go_assert(!this->is_method());
5842 go_assert(this->closure_var_ == NULL);
5843 if (this->descriptor_ == NULL)
5844 this->descriptor_ = Expression::make_func_descriptor(no);
5845 return this->descriptor_;
5848 // Get a pointer to the variable representing the defer stack for this
5849 // function, making it if necessary. The value of the variable is set
5850 // by the runtime routines to true if the function is returning,
5851 // rather than panicing through. A pointer to this variable is used
5852 // as a marker for the functions on the defer stack associated with
5853 // this function. A function-specific variable permits inlining a
5854 // function which uses defer.
5856 Expression*
5857 Function::defer_stack(Location location)
5859 if (this->defer_stack_ == NULL)
5861 Type* t = Type::lookup_bool_type();
5862 Expression* n = Expression::make_boolean(false, location);
5863 this->defer_stack_ = Statement::make_temporary(t, n, location);
5864 this->defer_stack_->set_is_address_taken();
5866 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5867 location);
5868 return Expression::make_unary(OPERATOR_AND, ref, location);
5871 // Export the function.
5873 void
5874 Function::export_func(Export* exp, const Named_object* no) const
5876 Block* block = NULL;
5877 if (this->export_for_inlining())
5878 block = this->block_;
5879 Function::export_func_with_type(exp, no, this->type_, this->results_,
5880 this->is_method() && this->nointerface(),
5881 this->asm_name(), block, this->location_);
5884 // Export a function with a type.
5886 void
5887 Function::export_func_with_type(Export* exp, const Named_object* no,
5888 const Function_type* fntype,
5889 Function::Results* result_vars,
5890 bool nointerface, const std::string& asm_name,
5891 Block* block, Location loc)
5893 exp->write_c_string("func ");
5895 if (nointerface)
5897 go_assert(fntype->is_method());
5898 exp->write_c_string("/*nointerface*/ ");
5901 if (!asm_name.empty())
5903 exp->write_c_string("/*asm ");
5904 exp->write_string(asm_name);
5905 exp->write_c_string(" */ ");
5908 if (fntype->is_method())
5910 exp->write_c_string("(");
5911 const Typed_identifier* receiver = fntype->receiver();
5912 exp->write_name(receiver->name());
5913 exp->write_escape(receiver->note());
5914 exp->write_c_string(" ");
5915 exp->write_type(receiver->type()->unalias());
5916 exp->write_c_string(") ");
5919 if (no->package() != NULL && !fntype->is_method())
5921 char buf[50];
5922 snprintf(buf, sizeof buf, "<p%d>", exp->package_index(no->package()));
5923 exp->write_c_string(buf);
5926 const std::string& name(no->name());
5927 if (!Gogo::is_hidden_name(name))
5928 exp->write_string(name);
5929 else
5931 exp->write_c_string(".");
5932 exp->write_string(Gogo::unpack_hidden_name(name));
5935 exp->write_c_string(" (");
5936 const Typed_identifier_list* parameters = fntype->parameters();
5937 if (parameters != NULL)
5939 size_t i = 0;
5940 bool is_varargs = fntype->is_varargs();
5941 bool first = true;
5942 for (Typed_identifier_list::const_iterator p = parameters->begin();
5943 p != parameters->end();
5944 ++p, ++i)
5946 if (first)
5947 first = false;
5948 else
5949 exp->write_c_string(", ");
5950 exp->write_name(p->name());
5951 exp->write_escape(p->note());
5952 exp->write_c_string(" ");
5953 if (!is_varargs || p + 1 != parameters->end())
5954 exp->write_type(p->type());
5955 else
5957 exp->write_c_string("...");
5958 exp->write_type(p->type()->array_type()->element_type());
5962 exp->write_c_string(")");
5964 const Typed_identifier_list* result_decls = fntype->results();
5965 if (result_decls != NULL)
5967 if (result_decls->size() == 1
5968 && result_decls->begin()->name().empty()
5969 && block == NULL)
5971 exp->write_c_string(" ");
5972 exp->write_type(result_decls->begin()->type());
5974 else
5976 exp->write_c_string(" (");
5977 bool first = true;
5978 Results::const_iterator pr;
5979 if (result_vars != NULL)
5980 pr = result_vars->begin();
5981 for (Typed_identifier_list::const_iterator pd = result_decls->begin();
5982 pd != result_decls->end();
5983 ++pd)
5985 if (first)
5986 first = false;
5987 else
5988 exp->write_c_string(", ");
5989 // We only use pr->name, which may be artificial, if
5990 // need it for inlining.
5991 if (block == NULL || result_vars == NULL)
5992 exp->write_name(pd->name());
5993 else
5994 exp->write_name((*pr)->name());
5995 exp->write_escape(pd->note());
5996 exp->write_c_string(" ");
5997 exp->write_type(pd->type());
5998 if (result_vars != NULL)
5999 ++pr;
6001 if (result_vars != NULL)
6002 go_assert(pr == result_vars->end());
6003 exp->write_c_string(")");
6007 if (block == NULL)
6008 exp->write_c_string("\n");
6009 else
6011 int indent = 1;
6012 if (fntype->is_method())
6013 indent++;
6015 Export_function_body efb(exp, indent);
6017 efb.indent();
6018 efb.write_c_string("// ");
6019 efb.write_string(Linemap::location_to_file(block->start_location()));
6020 efb.write_char(':');
6021 char buf[100];
6022 snprintf(buf, sizeof buf, "%d", Linemap::location_to_line(loc));
6023 efb.write_c_string(buf);
6024 efb.write_char('\n');
6025 block->export_block(&efb);
6027 const std::string& body(efb.body());
6029 snprintf(buf, sizeof buf, " <inl:%lu>\n",
6030 static_cast<unsigned long>(body.length()));
6031 exp->write_c_string(buf);
6033 exp->write_string(body);
6037 // Import a function.
6039 bool
6040 Function::import_func(Import* imp, std::string* pname,
6041 Package** ppkg, bool* pis_exported,
6042 Typed_identifier** preceiver,
6043 Typed_identifier_list** pparameters,
6044 Typed_identifier_list** presults,
6045 bool* is_varargs,
6046 bool* nointerface,
6047 std::string* asm_name,
6048 std::string* body)
6050 imp->require_c_string("func ");
6052 *nointerface = false;
6053 while (imp->match_c_string("/*"))
6055 imp->advance(2);
6056 if (imp->match_c_string("nointerface"))
6058 imp->require_c_string("nointerface*/ ");
6059 *nointerface = true;
6061 else if (imp->match_c_string("asm"))
6063 imp->require_c_string("asm ");
6064 *asm_name = imp->read_identifier();
6065 imp->require_c_string(" */ ");
6067 else
6069 go_error_at(imp->location(),
6070 "import error at %d: unrecognized function comment",
6071 imp->pos());
6072 return false;
6076 if (*nointerface)
6078 // Only a method can be nointerface.
6079 go_assert(imp->peek_char() == '(');
6082 *preceiver = NULL;
6083 if (imp->peek_char() == '(')
6085 imp->require_c_string("(");
6086 std::string name = imp->read_name();
6087 std::string escape_note = imp->read_escape();
6088 imp->require_c_string(" ");
6089 Type* rtype = imp->read_type();
6090 *preceiver = new Typed_identifier(name, rtype, imp->location());
6091 (*preceiver)->set_note(escape_note);
6092 imp->require_c_string(") ");
6095 if (!Import::read_qualified_identifier(imp, pname, ppkg, pis_exported))
6097 go_error_at(imp->location(),
6098 "import error at %d: bad function name in export data",
6099 imp->pos());
6100 return false;
6103 Typed_identifier_list* parameters;
6104 *is_varargs = false;
6105 imp->require_c_string(" (");
6106 if (imp->peek_char() == ')')
6107 parameters = NULL;
6108 else
6110 parameters = new Typed_identifier_list();
6111 while (true)
6113 std::string name = imp->read_name();
6114 std::string escape_note = imp->read_escape();
6115 imp->require_c_string(" ");
6117 if (imp->match_c_string("..."))
6119 imp->advance(3);
6120 *is_varargs = true;
6123 Type* ptype = imp->read_type();
6124 if (*is_varargs)
6125 ptype = Type::make_array_type(ptype, NULL);
6126 Typed_identifier t = Typed_identifier(name, ptype, imp->location());
6127 t.set_note(escape_note);
6128 parameters->push_back(t);
6129 if (imp->peek_char() != ',')
6130 break;
6131 go_assert(!*is_varargs);
6132 imp->require_c_string(", ");
6135 imp->require_c_string(")");
6136 *pparameters = parameters;
6138 Typed_identifier_list* results;
6139 if (imp->peek_char() != ' ' || imp->match_c_string(" <inl"))
6140 results = NULL;
6141 else
6143 results = new Typed_identifier_list();
6144 imp->require_c_string(" ");
6145 if (imp->peek_char() != '(')
6147 Type* rtype = imp->read_type();
6148 results->push_back(Typed_identifier("", rtype, imp->location()));
6150 else
6152 imp->require_c_string("(");
6153 while (true)
6155 std::string name = imp->read_name();
6156 std::string note = imp->read_escape();
6157 imp->require_c_string(" ");
6158 Type* rtype = imp->read_type();
6159 Typed_identifier t = Typed_identifier(name, rtype,
6160 imp->location());
6161 t.set_note(note);
6162 results->push_back(t);
6163 if (imp->peek_char() != ',')
6164 break;
6165 imp->require_c_string(", ");
6167 imp->require_c_string(")");
6170 *presults = results;
6172 if (!imp->match_c_string(" <inl:"))
6174 imp->require_semicolon_if_old_version();
6175 imp->require_c_string("\n");
6176 body->clear();
6178 else
6180 imp->require_c_string(" <inl:");
6181 std::string lenstr;
6182 int c;
6183 while (true)
6185 c = imp->peek_char();
6186 if (c < '0' || c > '9')
6187 break;
6188 lenstr += c;
6189 imp->get_char();
6191 imp->require_c_string(">\n");
6193 errno = 0;
6194 char* end;
6195 long llen = strtol(lenstr.c_str(), &end, 10);
6196 if (*end != '\0'
6197 || llen < 0
6198 || (llen == LONG_MAX && errno == ERANGE))
6200 go_error_at(imp->location(), "invalid inline function length %s",
6201 lenstr.c_str());
6202 return false;
6205 imp->read(static_cast<size_t>(llen), body);
6208 return true;
6211 // Get the backend name.
6213 void
6214 Function::backend_name(Gogo* gogo, Named_object* no, Backend_name *bname)
6216 if (!this->asm_name_.empty())
6217 bname->set_asm_name(this->asm_name_);
6218 else if (no->package() == NULL && no->name() == gogo->get_init_fn_name())
6220 // These names appear in the export data and are used
6221 // directly in the assembler code. If we change this here
6222 // we need to change Gogo::init_imports.
6223 bname->set_asm_name(no->name());
6225 else if (this->enclosing_ != NULL)
6227 // Rewrite the nested name to use the enclosing function name.
6228 // We don't do this earlier because we just store simple names
6229 // in a Named_object, not Backend_names.
6231 // The name was set by nested_function_name, which always
6232 // appends ..funcNNN. We want that to be our suffix.
6233 size_t pos = no->name().find("..func");
6234 go_assert(pos != std::string::npos);
6236 Named_object* enclosing = this->enclosing_;
6237 while (true)
6239 Named_object* parent = enclosing->func_value()->enclosing();
6240 if (parent == NULL)
6241 break;
6242 enclosing = parent;
6245 Type* rtype = NULL;
6246 if (enclosing->func_value()->type()->is_method())
6247 rtype = enclosing->func_value()->type()->receiver()->type();
6248 gogo->function_backend_name(enclosing->name(), enclosing->package(),
6249 rtype, bname);
6250 bname->append_suffix(no->name().substr(pos));
6252 else
6254 Type* rtype = NULL;
6255 if (this->type_->is_method())
6256 rtype = this->type_->receiver()->type();
6257 gogo->function_backend_name(no->name(), no->package(), rtype, bname);
6261 // Get the backend representation.
6263 Bfunction*
6264 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
6266 if (this->fndecl_ == NULL)
6268 unsigned int flags = 0;
6269 if (no->package() != NULL)
6271 // Functions defined in other packages must be visible.
6272 flags |= Backend::function_is_visible;
6274 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
6276 else if (Gogo::unpack_hidden_name(no->name()) == "init"
6277 && !this->type_->is_method())
6279 else if (no->name() == gogo->get_init_fn_name())
6280 flags |= Backend::function_is_visible;
6281 else if (Gogo::unpack_hidden_name(no->name()) == "main"
6282 && gogo->is_main_package())
6283 flags |= Backend::function_is_visible;
6284 // Methods have to be public even if they are hidden because
6285 // they can be pulled into type descriptors when using
6286 // anonymous fields.
6287 else if (!Gogo::is_hidden_name(no->name())
6288 || this->type_->is_method())
6290 if (!this->is_unnamed_type_stub_method_)
6291 flags |= Backend::function_is_visible;
6294 if (!this->asm_name_.empty())
6296 // If an assembler name is explicitly specified, there must
6297 // be some reason to refer to the symbol from a different
6298 // object file.
6299 flags |= Backend::function_is_visible;
6302 // If an inline body refers to this function, then it
6303 // needs to be visible in the symbol table.
6304 if (this->is_referenced_by_inline_)
6305 flags |= Backend::function_is_visible;
6307 // A go:linkname directive can be used to force a function to be
6308 // visible.
6309 if (this->is_exported_by_linkname_)
6310 flags |= Backend::function_is_visible;
6312 // If a function calls the predeclared recover function, we
6313 // can't inline it, because recover behaves differently in a
6314 // function passed directly to defer. If this is a recover
6315 // thunk that we built to test whether a function can be
6316 // recovered, we can't inline it, because that will mess up
6317 // our return address comparison.
6318 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
6320 // If a function calls __go_set_defer_retaddr, then mark it as
6321 // uninlinable. This prevents the GCC backend from splitting
6322 // the function; splitting the function is a bad idea because we
6323 // want the return address label to be in the same function as
6324 // the call.
6325 if (this->calls_defer_retaddr_)
6326 is_inlinable = false;
6328 // Check the //go:noinline compiler directive.
6329 if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
6330 is_inlinable = false;
6332 if (is_inlinable)
6333 flags |= Backend::function_is_inlinable;
6335 // If this is a thunk created to call a function which calls
6336 // the predeclared recover function, we need to disable
6337 // stack splitting for the thunk.
6338 bool disable_split_stack = this->is_recover_thunk_;
6340 // Check the //go:nosplit compiler directive.
6341 if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
6342 disable_split_stack = true;
6344 if (disable_split_stack)
6345 flags |= Backend::function_no_split_stack;
6347 // This should go into a unique section if that has been
6348 // requested elsewhere, or if this is a nointerface function.
6349 // We want to put a nointerface function into a unique section
6350 // because there is a good chance that the linker garbage
6351 // collection can discard it.
6352 if (this->in_unique_section_
6353 || (this->is_method() && this->nointerface()))
6354 flags |= Backend::function_in_unique_section;
6356 if (this->is_inline_only_)
6357 flags |= Backend::function_only_inline;
6359 Btype* functype = this->type_->get_backend_fntype(gogo);
6361 Backend_name bname;
6362 this->backend_name(gogo, no, &bname);
6364 this->fndecl_ = gogo->backend()->function(functype,
6365 bname.name(),
6366 bname.optional_asm_name(),
6367 flags,
6368 this->location());
6370 return this->fndecl_;
6373 // Get the backend name.
6375 void
6376 Function_declaration::backend_name(Gogo* gogo, Named_object* no,
6377 Backend_name* bname)
6379 if (!this->asm_name_.empty())
6380 bname->set_asm_name(this->asm_name_);
6381 else
6383 Type* rtype = NULL;
6384 if (this->fntype_->is_method())
6385 rtype = this->fntype_->receiver()->type();
6386 gogo->function_backend_name(no->name(), no->package(), rtype, bname);
6390 // Get the backend representation.
6392 Bfunction*
6393 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
6395 if (this->fndecl_ == NULL)
6397 unsigned int flags =
6398 (Backend::function_is_visible
6399 | Backend::function_is_declaration
6400 | Backend::function_is_inlinable);
6402 // Let Go code use an asm declaration to pick up a builtin
6403 // function.
6404 if (!this->asm_name_.empty())
6406 Bfunction* builtin_decl =
6407 gogo->backend()->lookup_builtin(this->asm_name_);
6408 if (builtin_decl != NULL)
6410 this->fndecl_ = builtin_decl;
6411 return this->fndecl_;
6414 if (this->asm_name_ == "runtime.gopanic"
6415 || this->asm_name_.compare(0, 13, "runtime.panic") == 0
6416 || this->asm_name_.compare(0, 15, "runtime.goPanic") == 0
6417 || this->asm_name_ == "runtime.block")
6418 flags |= Backend::function_does_not_return;
6421 Btype* functype = this->fntype_->get_backend_fntype(gogo);
6423 Backend_name bname;
6424 this->backend_name(gogo, no, &bname);
6426 this->fndecl_ = gogo->backend()->function(functype,
6427 bname.name(),
6428 bname.optional_asm_name(),
6429 flags,
6430 this->location());
6433 return this->fndecl_;
6436 // Build the descriptor for a function declaration. This won't
6437 // necessarily happen if the package has just a declaration for the
6438 // function and no other reference to it, but we may still need the
6439 // descriptor for references from other packages.
6440 void
6441 Function_declaration::build_backend_descriptor(Gogo* gogo)
6443 if (this->descriptor_ != NULL)
6445 Translate_context context(gogo, NULL, NULL, NULL);
6446 this->descriptor_->get_backend(&context);
6450 // Check that the types used in this declaration's signature are defined.
6451 // Reports errors for any undefined type.
6453 void
6454 Function_declaration::check_types() const
6456 // Calling Type::base will give errors for any undefined types.
6457 Function_type* fntype = this->type();
6458 if (fntype->receiver() != NULL)
6459 fntype->receiver()->type()->base();
6460 if (fntype->parameters() != NULL)
6462 const Typed_identifier_list* params = fntype->parameters();
6463 for (Typed_identifier_list::const_iterator p = params->begin();
6464 p != params->end();
6465 ++p)
6466 p->type()->base();
6470 // Return the function's decl after it has been built.
6472 Bfunction*
6473 Function::get_decl() const
6475 go_assert(this->fndecl_ != NULL);
6476 return this->fndecl_;
6479 // Build the backend representation for the function code.
6481 void
6482 Function::build(Gogo* gogo, Named_object* named_function)
6484 Translate_context context(gogo, named_function, NULL, NULL);
6486 // A list of parameter variables for this function.
6487 std::vector<Bvariable*> param_vars;
6489 // Variables that need to be declared for this function and their
6490 // initial values.
6491 std::vector<Bvariable*> vars;
6492 std::vector<Expression*> var_inits;
6493 std::vector<Statement*> var_decls_stmts;
6494 for (Bindings::const_definitions_iterator p =
6495 this->block_->bindings()->begin_definitions();
6496 p != this->block_->bindings()->end_definitions();
6497 ++p)
6499 Location loc = (*p)->location();
6500 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
6502 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6503 Bvariable* parm_bvar = bvar;
6505 // We always pass the receiver to a method as a pointer. If
6506 // the receiver is declared as a non-pointer type, then we
6507 // copy the value into a local variable. For direct interface
6508 // type we pack the pointer into the type.
6509 if ((*p)->var_value()->is_receiver()
6510 && (*p)->var_value()->type()->points_to() == NULL)
6512 std::string name = (*p)->name() + ".pointer";
6513 Type* var_type = (*p)->var_value()->type();
6514 Variable* parm_var =
6515 new Variable(Type::make_pointer_type(var_type), NULL, false,
6516 true, false, loc);
6517 Named_object* parm_no =
6518 Named_object::make_variable(name, NULL, parm_var);
6519 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6521 vars.push_back(bvar);
6523 Expression* parm_ref =
6524 Expression::make_var_reference(parm_no, loc);
6525 Type* recv_type = (*p)->var_value()->type();
6526 if (recv_type->is_direct_iface_type())
6527 parm_ref = Expression::pack_direct_iface(recv_type, parm_ref, loc);
6528 else
6529 parm_ref =
6530 Expression::make_dereference(parm_ref,
6531 Expression::NIL_CHECK_NEEDED,
6532 loc);
6533 if ((*p)->var_value()->is_in_heap())
6534 parm_ref = Expression::make_heap_expression(parm_ref, loc);
6535 var_inits.push_back(parm_ref);
6537 else if ((*p)->var_value()->is_in_heap())
6539 // If we take the address of a parameter, then we need
6540 // to copy it into the heap.
6541 std::string parm_name = (*p)->name() + ".param";
6542 Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
6543 false, true, false, loc);
6544 Named_object* parm_no =
6545 Named_object::make_variable(parm_name, NULL, parm_var);
6546 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6548 vars.push_back(bvar);
6549 Expression* var_ref =
6550 Expression::make_var_reference(parm_no, loc);
6551 var_ref = Expression::make_heap_expression(var_ref, loc);
6552 var_inits.push_back(var_ref);
6554 param_vars.push_back(parm_bvar);
6556 else if ((*p)->is_result_variable())
6558 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6560 Type* type = (*p)->result_var_value()->type();
6561 Expression* init;
6562 if (!(*p)->result_var_value()->is_in_heap())
6564 Btype* btype = type->get_backend(gogo);
6565 Bexpression* binit = gogo->backend()->zero_expression(btype);
6566 init = Expression::make_backend(binit, type, loc);
6568 else
6569 init = Expression::make_allocation(type, loc);
6571 vars.push_back(bvar);
6572 var_inits.push_back(init);
6574 else if (this->defer_stack_ != NULL
6575 && (*p)->is_variable()
6576 && (*p)->var_value()->is_non_escaping_address_taken()
6577 && !(*p)->var_value()->is_in_heap())
6579 // Local variable captured by deferred closure needs to be live
6580 // until the end of the function. We create a top-level
6581 // declaration for it.
6582 // TODO: we don't need to do this if the variable is not captured
6583 // by the defer closure. There is no easy way to check it here,
6584 // so we do this for all address-taken variables for now.
6585 Variable* var = (*p)->var_value();
6586 Temporary_statement* ts =
6587 Statement::make_temporary(var->type(), NULL, var->location());
6588 ts->set_is_address_taken();
6589 var->set_toplevel_decl(ts);
6590 var_decls_stmts.push_back(ts);
6593 if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
6595 go_assert(saw_errors());
6596 return;
6599 // If we need a closure variable, make sure to create it.
6600 // It gets installed in the function as a side effect of creation.
6601 if (this->closure_var_ != NULL)
6603 go_assert(this->closure_var_->var_value()->is_closure());
6604 this->closure_var_->get_backend_variable(gogo, named_function);
6607 if (this->block_ != NULL)
6609 // Declare variables if necessary.
6610 Bblock* var_decls = NULL;
6611 std::vector<Bstatement*> var_decls_bstmt_list;
6612 Bstatement* defer_init = NULL;
6613 if (!vars.empty() || this->defer_stack_ != NULL)
6615 var_decls =
6616 gogo->backend()->block(this->fndecl_, NULL, vars,
6617 this->block_->start_location(),
6618 this->block_->end_location());
6620 if (this->defer_stack_ != NULL)
6622 Translate_context dcontext(gogo, named_function, this->block_,
6623 var_decls);
6624 defer_init = this->defer_stack_->get_backend(&dcontext);
6625 var_decls_bstmt_list.push_back(defer_init);
6626 for (std::vector<Statement*>::iterator p = var_decls_stmts.begin();
6627 p != var_decls_stmts.end();
6628 ++p)
6630 Bstatement* bstmt = (*p)->get_backend(&dcontext);
6631 var_decls_bstmt_list.push_back(bstmt);
6636 // Build the backend representation for all the statements in the
6637 // function.
6638 Translate_context bcontext(gogo, named_function, NULL, NULL);
6639 Bblock* code_block = this->block_->get_backend(&bcontext);
6641 // Initialize variables if necessary.
6642 Translate_context icontext(gogo, named_function, this->block_,
6643 var_decls);
6644 std::vector<Bstatement*> init;
6645 go_assert(vars.size() == var_inits.size());
6646 for (size_t i = 0; i < vars.size(); ++i)
6648 Bexpression* binit = var_inits[i]->get_backend(&icontext);
6649 Bstatement* init_stmt =
6650 gogo->backend()->init_statement(this->fndecl_, vars[i],
6651 binit);
6652 init.push_back(init_stmt);
6654 Bstatement* var_init = gogo->backend()->statement_list(init);
6656 // Initialize all variables before executing this code block.
6657 Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
6658 code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
6660 // If we have a defer stack, initialize it at the start of a
6661 // function.
6662 Bstatement* except = NULL;
6663 Bstatement* fini = NULL;
6664 if (defer_init != NULL)
6666 // Clean up the defer stack when we leave the function.
6667 this->build_defer_wrapper(gogo, named_function, &except, &fini);
6669 // Wrap the code for this function in an exception handler to handle
6670 // defer calls.
6671 code_stmt =
6672 gogo->backend()->exception_handler_statement(code_stmt,
6673 except, fini,
6674 this->location_);
6677 // Stick the code into the block we built for the receiver, if
6678 // we built one.
6679 if (var_decls != NULL)
6681 var_decls_bstmt_list.push_back(code_stmt);
6682 gogo->backend()->block_add_statements(var_decls, var_decls_bstmt_list);
6683 code_stmt = gogo->backend()->block_statement(var_decls);
6686 if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
6688 go_assert(saw_errors());
6689 return;
6693 // If we created a descriptor for the function, make sure we emit it.
6694 if (this->descriptor_ != NULL)
6696 Translate_context dcontext(gogo, NULL, NULL, NULL);
6697 this->descriptor_->get_backend(&dcontext);
6701 // Build the wrappers around function code needed if the function has
6702 // any defer statements. This sets *EXCEPT to an exception handler
6703 // and *FINI to a finally handler.
6705 void
6706 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
6707 Bstatement** except, Bstatement** fini)
6709 Location end_loc = this->block_->end_location();
6711 // Add an exception handler. This is used if a panic occurs. Its
6712 // purpose is to stop the stack unwinding if a deferred function
6713 // calls recover. There are more details in
6714 // libgo/runtime/go-unwind.c.
6716 std::vector<Bstatement*> stmts;
6717 Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6718 this->defer_stack(end_loc));
6719 Translate_context context(gogo, named_function, NULL, NULL);
6720 Bexpression* defer = call->get_backend(&context);
6721 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
6723 Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
6724 if (ret_bstmt != NULL)
6725 stmts.push_back(ret_bstmt);
6727 go_assert(*except == NULL);
6728 *except = gogo->backend()->statement_list(stmts);
6730 call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6731 this->defer_stack(end_loc));
6732 defer = call->get_backend(&context);
6734 call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
6735 this->defer_stack(end_loc));
6736 Bexpression* undefer = call->get_backend(&context);
6737 Bstatement* function_defer =
6738 gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
6739 end_loc);
6740 stmts = std::vector<Bstatement*>(1, function_defer);
6741 if (this->type_->results() != NULL
6742 && !this->type_->results()->empty()
6743 && !this->type_->results()->front().name().empty())
6745 // If the result variables are named, and we are returning from
6746 // this function rather than panicing through it, we need to
6747 // return them again, because they might have been changed by a
6748 // defer function. The runtime routines set the defer_stack
6749 // variable to true if we are returning from this function.
6751 ret_bstmt = this->return_value(gogo, named_function, end_loc);
6752 Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
6753 Bexpression* ret =
6754 gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
6755 Expression* ref =
6756 Expression::make_temporary_reference(this->defer_stack_, end_loc);
6757 Bexpression* bref = ref->get_backend(&context);
6758 ret = gogo->backend()->conditional_expression(this->fndecl_,
6759 NULL, bref, ret, NULL,
6760 end_loc);
6761 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
6764 go_assert(*fini == NULL);
6765 *fini = gogo->backend()->statement_list(stmts);
6768 // Return the statement that assigns values to this function's result struct.
6770 Bstatement*
6771 Function::return_value(Gogo* gogo, Named_object* named_function,
6772 Location location) const
6774 const Typed_identifier_list* results = this->type_->results();
6775 if (results == NULL || results->empty())
6776 return NULL;
6778 go_assert(this->results_ != NULL);
6779 if (this->results_->size() != results->size())
6781 go_assert(saw_errors());
6782 return gogo->backend()->error_statement();
6785 std::vector<Bexpression*> vals(results->size());
6786 for (size_t i = 0; i < vals.size(); ++i)
6788 Named_object* no = (*this->results_)[i];
6789 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
6790 Bexpression* val = gogo->backend()->var_expression(bvar, location);
6791 if (no->result_var_value()->is_in_heap())
6793 Btype* bt = no->result_var_value()->type()->get_backend(gogo);
6794 val = gogo->backend()->indirect_expression(bt, val, true, location);
6796 vals[i] = val;
6798 return gogo->backend()->return_statement(this->fndecl_, vals, location);
6801 // Class Block.
6803 Block::Block(Block* enclosing, Location location)
6804 : enclosing_(enclosing), statements_(),
6805 bindings_(new Bindings(enclosing == NULL
6806 ? NULL
6807 : enclosing->bindings())),
6808 start_location_(location),
6809 end_location_(Linemap::unknown_location())
6813 // Add a statement to a block.
6815 void
6816 Block::add_statement(Statement* statement)
6818 this->statements_.push_back(statement);
6821 // Add a statement to the front of a block. This is slow but is only
6822 // used for reference counts of parameters.
6824 void
6825 Block::add_statement_at_front(Statement* statement)
6827 this->statements_.insert(this->statements_.begin(), statement);
6830 // Replace a statement in a block.
6832 void
6833 Block::replace_statement(size_t index, Statement* s)
6835 go_assert(index < this->statements_.size());
6836 this->statements_[index] = s;
6839 // Add a statement before another statement.
6841 void
6842 Block::insert_statement_before(size_t index, Statement* s)
6844 go_assert(index < this->statements_.size());
6845 this->statements_.insert(this->statements_.begin() + index, s);
6848 // Add a statement after another statement.
6850 void
6851 Block::insert_statement_after(size_t index, Statement* s)
6853 go_assert(index < this->statements_.size());
6854 this->statements_.insert(this->statements_.begin() + index + 1, s);
6857 // Traverse the tree.
6860 Block::traverse(Traverse* traverse)
6862 unsigned int traverse_mask = traverse->traverse_mask();
6864 if ((traverse_mask & Traverse::traverse_blocks) != 0)
6866 int t = traverse->block(this);
6867 if (t == TRAVERSE_EXIT)
6868 return TRAVERSE_EXIT;
6869 else if (t == TRAVERSE_SKIP_COMPONENTS)
6870 return TRAVERSE_CONTINUE;
6873 if ((traverse_mask
6874 & (Traverse::traverse_variables
6875 | Traverse::traverse_constants
6876 | Traverse::traverse_expressions
6877 | Traverse::traverse_types)) != 0)
6879 for (Bindings::const_definitions_iterator pb =
6880 this->bindings_->begin_definitions();
6881 pb != this->bindings_->end_definitions();
6882 ++pb)
6884 if ((*pb)->traverse(traverse, false) == TRAVERSE_EXIT)
6885 return TRAVERSE_EXIT;
6889 // No point in checking traverse_mask here--if we got here we always
6890 // want to walk the statements. The traversal can insert new
6891 // statements before or after the current statement. Inserting
6892 // statements before the current statement requires updating I via
6893 // the pointer; those statements will not be traversed. Any new
6894 // statements inserted after the current statement will be traversed
6895 // in their turn.
6896 for (size_t i = 0; i < this->statements_.size(); ++i)
6898 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
6899 return TRAVERSE_EXIT;
6902 return TRAVERSE_CONTINUE;
6905 // Work out types for unspecified variables and constants.
6907 void
6908 Block::determine_types()
6910 for (Bindings::const_definitions_iterator pb =
6911 this->bindings_->begin_definitions();
6912 pb != this->bindings_->end_definitions();
6913 ++pb)
6915 if ((*pb)->is_variable())
6916 (*pb)->var_value()->determine_type();
6917 else if ((*pb)->is_const())
6918 (*pb)->const_value()->determine_type();
6921 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6922 ps != this->statements_.end();
6923 ++ps)
6924 (*ps)->determine_types();
6927 // Return true if the statements in this block may fall through.
6929 bool
6930 Block::may_fall_through() const
6932 if (this->statements_.empty())
6933 return true;
6934 return this->statements_.back()->may_fall_through();
6937 // Write export data for a block.
6939 void
6940 Block::export_block(Export_function_body* efb)
6942 for (Block::iterator p = this->begin();
6943 p != this->end();
6944 ++p)
6946 efb->indent();
6948 efb->increment_indent();
6949 (*p)->export_statement(efb);
6950 efb->decrement_indent();
6952 Location loc = (*p)->location();
6953 if ((*p)->is_block_statement())
6955 // For a block we put the start location on the first brace
6956 // in Block_statement::do_export_statement. Here we put the
6957 // end location on the final brace.
6958 loc = (*p)->block_statement()->block()->end_location();
6960 char buf[50];
6961 snprintf(buf, sizeof buf, " //%d\n", Linemap::location_to_line(loc));
6962 efb->write_c_string(buf);
6966 // Add exported block data to SET, reading from BODY starting at OFF.
6967 // Returns whether the import succeeded.
6969 bool
6970 Block::import_block(Block* set, Import_function_body *ifb, Location loc)
6972 Location eloc = ifb->location();
6973 Location sloc = loc;
6974 const std::string& body(ifb->body());
6975 size_t off = ifb->off();
6976 while (off < body.length())
6978 int indent = ifb->indent();
6979 if (off + indent >= body.length())
6981 go_error_at(eloc,
6982 "invalid export data for %qs: insufficient indentation",
6983 ifb->name().c_str());
6984 return false;
6986 for (int i = 0; i < indent - 1; i++)
6988 if (body[off + i] != ' ')
6990 go_error_at(eloc,
6991 "invalid export data for %qs: bad indentation",
6992 ifb->name().c_str());
6993 return false;
6997 bool at_end = false;
6998 if (body[off + indent - 1] == '}')
6999 at_end = true;
7000 else if (body[off + indent - 1] != ' ')
7002 go_error_at(eloc,
7003 "invalid export data for %qs: bad indentation",
7004 ifb->name().c_str());
7005 return false;
7008 off += indent;
7010 size_t nl = body.find('\n', off);
7011 if (nl == std::string::npos)
7013 go_error_at(eloc, "invalid export data for %qs: missing newline",
7014 ifb->name().c_str());
7015 return false;
7018 size_t lineno_pos = body.find(" //", off);
7019 if (lineno_pos == std::string::npos || lineno_pos >= nl)
7021 go_error_at(eloc, "invalid export data for %qs: missing line number",
7022 ifb->name().c_str());
7023 return false;
7026 unsigned int lineno = 0;
7027 for (size_t i = lineno_pos + 3; i < nl; ++i)
7029 char c = body[i];
7030 if (c < '0' || c > '9')
7032 go_error_at(loc,
7033 "invalid export data for %qs: invalid line number",
7034 ifb->name().c_str());
7035 return false;
7037 lineno = lineno * 10 + c - '0';
7040 ifb->gogo()->linemap()->start_line(lineno, 1);
7041 sloc = ifb->gogo()->linemap()->get_location(0);
7043 if (at_end)
7045 // An if statement can have an "else" following the "}", in
7046 // which case we want to leave the offset where it is, just
7047 // after the "}". We don't get the block ending location
7048 // quite right for if statements.
7049 if (body.compare(off, 6, " else ") != 0)
7050 off = nl + 1;
7051 break;
7054 ifb->set_off(off);
7055 Statement* s = Statement::import_statement(ifb, sloc);
7056 if (s == NULL)
7057 return false;
7059 set->add_statement(s);
7061 size_t at = ifb->off();
7062 if (at < nl + 1)
7063 off = nl + 1;
7064 else
7065 off = at;
7068 ifb->set_off(off);
7069 set->set_end_location(sloc);
7070 return true;
7073 // Convert a block to the backend representation.
7075 Bblock*
7076 Block::get_backend(Translate_context* context)
7078 Gogo* gogo = context->gogo();
7079 Named_object* function = context->function();
7080 std::vector<Bvariable*> vars;
7081 vars.reserve(this->bindings_->size_definitions());
7082 for (Bindings::const_definitions_iterator pv =
7083 this->bindings_->begin_definitions();
7084 pv != this->bindings_->end_definitions();
7085 ++pv)
7087 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
7088 vars.push_back((*pv)->get_backend_variable(gogo, function));
7091 go_assert(function != NULL);
7092 Bfunction* bfunction =
7093 function->func_value()->get_or_make_decl(gogo, function);
7094 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
7095 vars, this->start_location_,
7096 this->end_location_);
7098 Translate_context subcontext(gogo, function, this, ret);
7099 std::vector<Bstatement*> bstatements;
7100 bstatements.reserve(this->statements_.size());
7101 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
7102 p != this->statements_.end();
7103 ++p)
7104 bstatements.push_back((*p)->get_backend(&subcontext));
7106 context->backend()->block_add_statements(ret, bstatements);
7108 return ret;
7111 // Class Bindings_snapshot.
7113 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
7114 : block_(b), counts_(), location_(location)
7116 while (b != NULL)
7118 this->counts_.push_back(b->bindings()->size_definitions());
7119 b = b->enclosing();
7123 // Report errors appropriate for a goto from B to this.
7125 void
7126 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
7128 size_t dummy;
7129 if (!this->check_goto_block(loc, b, this->block_, &dummy))
7130 return;
7131 this->check_goto_defs(loc, this->block_,
7132 this->block_->bindings()->size_definitions(),
7133 this->counts_[0]);
7136 // Report errors appropriate for a goto from this to B.
7138 void
7139 Bindings_snapshot::check_goto_to(const Block* b)
7141 size_t index;
7142 if (!this->check_goto_block(this->location_, this->block_, b, &index))
7143 return;
7144 this->check_goto_defs(this->location_, b, this->counts_[index],
7145 b->bindings()->size_definitions());
7148 // Report errors appropriate for a goto at LOC from BFROM to BTO.
7149 // Return true if all is well, false if we reported an error. If this
7150 // returns true, it sets *PINDEX to the number of blocks BTO is above
7151 // BFROM.
7153 bool
7154 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
7155 const Block* bto, size_t* pindex)
7157 // It is an error if BTO is not either BFROM or above BFROM.
7158 size_t index = 0;
7159 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
7161 if (pb == NULL)
7163 go_error_at(loc, "goto jumps into block");
7164 go_inform(bto->start_location(), "goto target block starts here");
7165 return false;
7168 *pindex = index;
7169 return true;
7172 // Report errors appropriate for a goto at LOC ending at BLOCK, where
7173 // CFROM is the number of names defined at the point of the goto and
7174 // CTO is the number of names defined at the point of the label.
7176 void
7177 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
7178 size_t cfrom, size_t cto)
7180 if (cfrom < cto)
7182 Bindings::const_definitions_iterator p =
7183 block->bindings()->begin_definitions();
7184 for (size_t i = 0; i < cfrom; ++i)
7186 go_assert(p != block->bindings()->end_definitions());
7187 ++p;
7189 go_assert(p != block->bindings()->end_definitions());
7191 for (; p != block->bindings()->end_definitions(); ++p)
7193 if ((*p)->is_variable())
7195 std::string n = (*p)->message_name();
7196 go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
7197 go_inform((*p)->location(), "%qs defined here", n.c_str());
7203 // Class Function_declaration.
7205 // Whether this declares a method.
7207 bool
7208 Function_declaration::is_method() const
7210 return this->fntype_->is_method();
7213 // Whether this method should not be included in the type descriptor.
7215 bool
7216 Function_declaration::nointerface() const
7218 go_assert(this->is_method());
7219 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
7222 // Record that this method should not be included in the type
7223 // descriptor.
7225 void
7226 Function_declaration::set_nointerface()
7228 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
7231 // Set the receiver type. This is used to remove aliases.
7233 void
7234 Function_declaration::set_receiver_type(Type* rtype)
7236 Function_type* oft = this->fntype_;
7237 Typed_identifier* rec = new Typed_identifier(oft->receiver()->name(),
7238 rtype,
7239 oft->receiver()->location());
7240 Typed_identifier_list* parameters = NULL;
7241 if (oft->parameters() != NULL)
7242 parameters = oft->parameters()->copy();
7243 Typed_identifier_list* results = NULL;
7244 if (oft->results() != NULL)
7245 results = oft->results()->copy();
7246 Function_type* nft = Type::make_function_type(rec, parameters, results,
7247 oft->location());
7248 this->fntype_ = nft;
7251 // Import an inlinable function. This is used for an inlinable
7252 // function whose body is recorded in the export data. Parse the
7253 // export data into a Block and create a regular function using that
7254 // Block as its body. Redeclare this function declaration as the
7255 // function.
7257 void
7258 Function_declaration::import_function_body(Gogo* gogo, Named_object* no)
7260 go_assert(no->func_declaration_value() == this);
7261 go_assert(no->package() != NULL);
7262 const std::string& body(this->imported_body_);
7263 go_assert(!body.empty());
7265 // Read the "//FILE:LINE" comment starts the export data.
7267 size_t indent = 1;
7268 if (this->is_method())
7269 indent = 2;
7270 size_t i = 0;
7271 for (; i < indent; i++)
7273 if (body.at(i) != ' ')
7275 go_error_at(this->location_,
7276 "invalid export body for %qs: bad initial indentation",
7277 no->message_name().c_str());
7278 return;
7282 if (body.substr(i, 2) != "//")
7284 go_error_at(this->location_,
7285 "invalid export body for %qs: missing file comment",
7286 no->message_name().c_str());
7287 return;
7290 size_t colon = body.find(':', i + 2);
7291 size_t nl = body.find('\n', i + 2);
7292 if (nl == std::string::npos)
7294 go_error_at(this->location_,
7295 "invalid export body for %qs: missing file name",
7296 no->message_name().c_str());
7297 return;
7299 if (colon == std::string::npos || nl < colon)
7301 go_error_at(this->location_,
7302 "invalid export body for %qs: missing initial line number",
7303 no->message_name().c_str());
7304 return;
7307 std::string file = body.substr(i + 2, colon - (i + 2));
7308 std::string linestr = body.substr(colon + 1, nl - (colon + 1));
7309 char* end;
7310 long linenol = strtol(linestr.c_str(), &end, 10);
7311 if (*end != '\0')
7313 go_error_at(this->location_,
7314 "invalid export body for %qs: invalid initial line number",
7315 no->message_name().c_str());
7316 return;
7318 unsigned int lineno = static_cast<unsigned int>(linenol);
7320 // Turn the file/line into a location.
7322 char* alc = new char[file.length() + 1];
7323 memcpy(alc, file.data(), file.length());
7324 alc[file.length()] = '\0';
7325 gogo->linemap()->start_file(alc, lineno);
7326 gogo->linemap()->start_line(lineno, 1);
7327 Location start_loc = gogo->linemap()->get_location(0);
7329 // Define the function with an outer block that declares the
7330 // parameters.
7332 Function_type* fntype = this->fntype_;
7334 Block* outer = new Block(NULL, start_loc);
7336 Function* fn = new Function(fntype, NULL, outer, start_loc);
7337 fn->set_is_inline_only();
7339 if (fntype->is_method())
7341 if (this->nointerface())
7342 fn->set_nointerface();
7343 const Typed_identifier* receiver = fntype->receiver();
7344 Variable* recv_param = new Variable(receiver->type(), NULL, false,
7345 true, true, start_loc);
7347 std::string rname = receiver->name();
7348 unsigned rcounter = 0;
7350 // We need to give a nameless receiver a name to avoid having it
7351 // clash with some other nameless param. FIXME.
7352 Gogo::rename_if_empty(&rname, "r", &rcounter);
7354 outer->bindings()->add_variable(rname, NULL, recv_param);
7357 const Typed_identifier_list* params = fntype->parameters();
7358 bool is_varargs = fntype->is_varargs();
7359 unsigned pcounter = 0;
7360 if (params != NULL)
7362 for (Typed_identifier_list::const_iterator p = params->begin();
7363 p != params->end();
7364 ++p)
7366 Variable* param = new Variable(p->type(), NULL, false, true, false,
7367 start_loc);
7368 if (is_varargs && p + 1 == params->end())
7369 param->set_is_varargs_parameter();
7371 std::string pname = p->name();
7373 // We need to give each nameless parameter a non-empty name to avoid
7374 // having it clash with some other nameless param. FIXME.
7375 Gogo::rename_if_empty(&pname, "p", &pcounter);
7377 outer->bindings()->add_variable(pname, NULL, param);
7381 fn->create_result_variables(gogo);
7383 if (!fntype->is_method())
7385 const Package* package = no->package();
7386 no = package->bindings()->add_function(no->name(), package, fn);
7388 else
7390 Named_type* rtype = fntype->receiver()->type()->deref()->named_type();
7391 go_assert(rtype != NULL);
7392 no = rtype->add_method(no->name(), fn);
7393 const Package* package = rtype->named_object()->package();
7394 package->bindings()->add_method(no);
7397 Import_function_body ifb(gogo, this->imp_, no, body, nl + 1, outer, indent);
7399 if (!Block::import_block(outer, &ifb, start_loc))
7400 return;
7402 gogo->lower_block(no, outer);
7403 outer->determine_types();
7405 gogo->add_imported_inline_function(no);
7408 // Return the function descriptor.
7410 Expression*
7411 Function_declaration::descriptor(Gogo*, Named_object* no)
7413 go_assert(!this->fntype_->is_method());
7414 if (this->descriptor_ == NULL)
7415 this->descriptor_ = Expression::make_func_descriptor(no);
7416 return this->descriptor_;
7419 // Class Variable.
7421 Variable::Variable(Type* type, Expression* init, bool is_global,
7422 bool is_parameter, bool is_receiver,
7423 Location location)
7424 : type_(type), init_(init), preinit_(NULL), location_(location),
7425 embeds_(NULL), backend_(NULL), is_global_(is_global),
7426 is_parameter_(is_parameter), is_closure_(false), is_receiver_(is_receiver),
7427 is_varargs_parameter_(false), is_global_sink_(false), is_used_(false),
7428 is_address_taken_(false), is_non_escaping_address_taken_(false),
7429 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
7430 type_from_init_tuple_(false), type_from_range_index_(false),
7431 type_from_range_value_(false), type_from_chan_element_(false),
7432 is_type_switch_var_(false), determined_type_(false),
7433 in_unique_section_(false), is_referenced_by_inline_(false),
7434 toplevel_decl_(NULL)
7436 go_assert(type != NULL || init != NULL);
7437 go_assert(!is_parameter || init == NULL);
7440 // Traverse the initializer expression.
7443 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
7445 if (this->preinit_ != NULL)
7447 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
7448 return TRAVERSE_EXIT;
7450 if (this->init_ != NULL
7451 && ((traverse_mask
7452 & (Traverse::traverse_expressions | Traverse::traverse_types))
7453 != 0))
7455 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
7456 return TRAVERSE_EXIT;
7458 return TRAVERSE_CONTINUE;
7461 // Lower the initialization expression after parsing is complete.
7463 void
7464 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
7465 Statement_inserter* inserter)
7467 Named_object* dep = gogo->var_depends_on(this);
7468 if (dep != NULL && dep->is_variable())
7469 dep->var_value()->lower_init_expression(gogo, function, inserter);
7471 if (this->embeds_ != NULL)
7473 // Now that we have seen any possible type aliases, convert the
7474 // go:embed directives into an initializer.
7475 go_assert(this->init_ == NULL && this->type_ != NULL);
7476 this->init_ = gogo->initializer_for_embeds(this->type_, this->embeds_,
7477 this->location_);
7478 delete this->embeds_;
7479 this->embeds_ = NULL;
7482 if (this->init_ != NULL && !this->init_is_lowered_)
7484 if (this->seen_)
7486 // We will give an error elsewhere, this is just to prevent
7487 // an infinite loop.
7488 return;
7490 this->seen_ = true;
7492 Statement_inserter global_inserter;
7493 if (this->is_global_)
7495 global_inserter = Statement_inserter(gogo, this);
7496 inserter = &global_inserter;
7499 gogo->lower_expression(function, inserter, &this->init_);
7501 this->seen_ = false;
7503 this->init_is_lowered_ = true;
7507 // Flatten the initialization expression after ordering evaluations.
7509 void
7510 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
7511 Statement_inserter* inserter)
7513 Named_object* dep = gogo->var_depends_on(this);
7514 if (dep != NULL && dep->is_variable())
7515 dep->var_value()->flatten_init_expression(gogo, function, inserter);
7517 if (this->init_ != NULL && !this->init_is_flattened_)
7519 if (this->seen_)
7521 // We will give an error elsewhere, this is just to prevent
7522 // an infinite loop.
7523 return;
7525 this->seen_ = true;
7527 Statement_inserter global_inserter;
7528 if (this->is_global_)
7530 global_inserter = Statement_inserter(gogo, this);
7531 inserter = &global_inserter;
7534 gogo->flatten_expression(function, inserter, &this->init_);
7536 // If an interface conversion is needed, we need a temporary
7537 // variable.
7538 if (this->type_ != NULL
7539 && !Type::are_identical(this->type_, this->init_->type(),
7540 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
7541 NULL)
7542 && this->init_->type()->interface_type() != NULL
7543 && !this->init_->is_multi_eval_safe())
7545 Temporary_statement* temp =
7546 Statement::make_temporary(NULL, this->init_, this->location_);
7547 inserter->insert(temp);
7548 this->init_ = Expression::make_temporary_reference(temp,
7549 this->location_);
7552 this->seen_ = false;
7553 this->init_is_flattened_ = true;
7557 // Get the preinit block.
7559 Block*
7560 Variable::preinit_block(Gogo* gogo)
7562 go_assert(this->is_global_);
7563 if (this->preinit_ == NULL)
7564 this->preinit_ = new Block(NULL, this->location());
7566 // If a global variable has a preinitialization statement, then we
7567 // need to have an initialization function.
7568 gogo->set_need_init_fn();
7570 return this->preinit_;
7573 // Add a statement to be run before the initialization expression.
7575 void
7576 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
7578 Block* b = this->preinit_block(gogo);
7579 b->add_statement(s);
7580 b->set_end_location(s->location());
7583 // Whether this variable has a type.
7585 bool
7586 Variable::has_type() const
7588 if (this->type_ == NULL)
7589 return false;
7591 // A variable created in a type switch case nil does not actually
7592 // have a type yet. It will be changed to use the initializer's
7593 // type in determine_type.
7594 if (this->is_type_switch_var_
7595 && this->type_->is_nil_constant_as_type())
7596 return false;
7598 return true;
7601 // In an assignment which sets a variable to a tuple of EXPR, return
7602 // the type of the first element of the tuple.
7604 Type*
7605 Variable::type_from_tuple(Expression* expr, bool report_error) const
7607 if (expr->map_index_expression() != NULL)
7609 Map_type* mt = expr->map_index_expression()->get_map_type();
7610 if (mt == NULL)
7611 return Type::make_error_type();
7612 return mt->val_type();
7614 else if (expr->receive_expression() != NULL)
7616 Expression* channel = expr->receive_expression()->channel();
7617 Type* channel_type = channel->type();
7618 if (channel_type->channel_type() == NULL)
7619 return Type::make_error_type();
7620 return channel_type->channel_type()->element_type();
7622 else
7624 if (report_error)
7625 go_error_at(this->location(), "invalid tuple definition");
7626 return Type::make_error_type();
7630 // Given EXPR used in a range clause, return either the index type or
7631 // the value type of the range, depending upon GET_INDEX_TYPE.
7633 Type*
7634 Variable::type_from_range(Expression* expr, bool get_index_type,
7635 bool report_error) const
7637 Type* t = expr->type();
7638 if (t->array_type() != NULL
7639 || (t->points_to() != NULL
7640 && t->points_to()->array_type() != NULL
7641 && !t->points_to()->is_slice_type()))
7643 if (get_index_type)
7644 return Type::lookup_integer_type("int");
7645 else
7646 return t->deref()->array_type()->element_type();
7648 else if (t->is_string_type())
7650 if (get_index_type)
7651 return Type::lookup_integer_type("int");
7652 else
7653 return Type::lookup_integer_type("int32");
7655 else if (t->map_type() != NULL)
7657 if (get_index_type)
7658 return t->map_type()->key_type();
7659 else
7660 return t->map_type()->val_type();
7662 else if (t->channel_type() != NULL)
7664 if (get_index_type)
7665 return t->channel_type()->element_type();
7666 else
7668 if (report_error)
7669 go_error_at(this->location(),
7670 ("invalid definition of value variable "
7671 "for channel range"));
7672 return Type::make_error_type();
7675 else
7677 if (report_error)
7678 go_error_at(this->location(), "invalid type for range clause");
7679 return Type::make_error_type();
7683 // EXPR should be a channel. Return the channel's element type.
7685 Type*
7686 Variable::type_from_chan_element(Expression* expr, bool report_error) const
7688 Type* t = expr->type();
7689 if (t->channel_type() != NULL)
7690 return t->channel_type()->element_type();
7691 else
7693 if (report_error)
7694 go_error_at(this->location(), "expected channel");
7695 return Type::make_error_type();
7699 // Return the type of the Variable. This may be called before
7700 // Variable::determine_type is called, which means that we may need to
7701 // get the type from the initializer. FIXME: If we combine lowering
7702 // with type determination, then this should be unnecessary.
7704 Type*
7705 Variable::type()
7707 // A variable in a type switch with a nil case will have the wrong
7708 // type here. This gets fixed up in determine_type, below.
7709 Type* type = this->type_;
7710 Expression* init = this->init_;
7711 if (this->is_type_switch_var_
7712 && type != NULL
7713 && this->type_->is_nil_constant_as_type())
7715 Type_guard_expression* tge = this->init_->type_guard_expression();
7716 go_assert(tge != NULL);
7717 init = tge->expr();
7718 type = NULL;
7721 if (this->seen_)
7723 if (this->type_ == NULL || !this->type_->is_error_type())
7725 go_error_at(this->location_, "variable initializer refers to itself");
7726 this->type_ = Type::make_error_type();
7728 return this->type_;
7731 this->seen_ = true;
7733 if (type != NULL)
7735 else if (this->type_from_init_tuple_)
7736 type = this->type_from_tuple(init, false);
7737 else if (this->type_from_range_index_ || this->type_from_range_value_)
7738 type = this->type_from_range(init, this->type_from_range_index_, false);
7739 else if (this->type_from_chan_element_)
7740 type = this->type_from_chan_element(init, false);
7741 else
7743 go_assert(init != NULL);
7744 type = init->type();
7745 go_assert(type != NULL);
7747 // Variables should not have abstract types.
7748 if (type->is_abstract())
7749 type = type->make_non_abstract_type();
7751 if (type->is_void_type())
7752 type = Type::make_error_type();
7755 this->seen_ = false;
7757 return type;
7760 // Fetch the type from a const pointer, in which case it should have
7761 // been set already.
7763 Type*
7764 Variable::type() const
7766 go_assert(this->type_ != NULL);
7767 return this->type_;
7770 // Set the type if necessary.
7772 void
7773 Variable::determine_type()
7775 if (this->determined_type_)
7776 return;
7777 this->determined_type_ = true;
7779 if (this->preinit_ != NULL)
7780 this->preinit_->determine_types();
7782 // A variable in a type switch with a nil case will have the wrong
7783 // type here. It will have an initializer which is a type guard.
7784 // We want to initialize it to the value without the type guard, and
7785 // use the type of that value as well.
7786 if (this->is_type_switch_var_
7787 && this->type_ != NULL
7788 && this->type_->is_nil_constant_as_type())
7790 Type_guard_expression* tge = this->init_->type_guard_expression();
7791 go_assert(tge != NULL);
7792 this->type_ = NULL;
7793 this->init_ = tge->expr();
7796 if (this->init_ == NULL)
7797 go_assert(this->type_ != NULL && !this->type_->is_abstract());
7798 else if (this->type_from_init_tuple_)
7800 Expression *init = this->init_;
7801 init->determine_type_no_context();
7802 this->type_ = this->type_from_tuple(init, true);
7803 this->init_ = NULL;
7805 else if (this->type_from_range_index_ || this->type_from_range_value_)
7807 Expression* init = this->init_;
7808 init->determine_type_no_context();
7809 this->type_ = this->type_from_range(init, this->type_from_range_index_,
7810 true);
7811 this->init_ = NULL;
7813 else if (this->type_from_chan_element_)
7815 Expression* init = this->init_;
7816 init->determine_type_no_context();
7817 this->type_ = this->type_from_chan_element(init, true);
7818 this->init_ = NULL;
7820 else
7822 Type_context context(this->type_, false);
7823 this->init_->determine_type(&context);
7824 if (this->type_ == NULL)
7826 Type* type = this->init_->type();
7827 go_assert(type != NULL);
7828 if (type->is_abstract())
7829 type = type->make_non_abstract_type();
7831 if (type->is_void_type())
7833 go_error_at(this->location_, "variable has no type");
7834 type = Type::make_error_type();
7836 else if (type->is_nil_type())
7838 go_error_at(this->location_, "variable defined to nil type");
7839 type = Type::make_error_type();
7841 else if (type->is_call_multiple_result_type())
7843 go_error_at(this->location_,
7844 "single variable set to multiple-value function call");
7845 type = Type::make_error_type();
7848 this->type_ = type;
7853 // Get the initial value of a variable. This does not
7854 // consider whether the variable is in the heap--it returns the
7855 // initial value as though it were always stored in the stack.
7857 Bexpression*
7858 Variable::get_init(Gogo* gogo, Named_object* function)
7860 go_assert(this->preinit_ == NULL);
7861 Location loc = this->location();
7862 if (this->init_ == NULL)
7864 go_assert(!this->is_parameter_);
7865 if (this->is_global_ || this->is_in_heap())
7866 return NULL;
7867 Btype* btype = this->type()->get_backend(gogo);
7868 return gogo->backend()->zero_expression(btype);
7870 else
7872 Translate_context context(gogo, function, NULL, NULL);
7873 Expression* init = Expression::make_cast(this->type(), this->init_, loc);
7874 return init->get_backend(&context);
7878 // Get the initial value of a variable when a block is required.
7879 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7881 Bstatement*
7882 Variable::get_init_block(Gogo* gogo, Named_object* function,
7883 Bvariable* var_decl)
7885 go_assert(this->preinit_ != NULL);
7887 // We want to add the variable assignment to the end of the preinit
7888 // block.
7890 Translate_context context(gogo, function, NULL, NULL);
7891 Bblock* bblock = this->preinit_->get_backend(&context);
7892 Bfunction* bfunction =
7893 function->func_value()->get_or_make_decl(gogo, function);
7895 // It's possible to have pre-init statements without an initializer
7896 // if the pre-init statements set the variable.
7897 Bstatement* decl_init = NULL;
7898 if (this->init_ != NULL)
7900 if (var_decl == NULL)
7902 Bexpression* init_bexpr = this->init_->get_backend(&context);
7903 decl_init = gogo->backend()->expression_statement(bfunction,
7904 init_bexpr);
7906 else
7908 Location loc = this->location();
7909 Expression* val_expr =
7910 Expression::make_cast(this->type(), this->init_, loc);
7911 Bexpression* val = val_expr->get_backend(&context);
7912 Bexpression* var_ref =
7913 gogo->backend()->var_expression(var_decl, loc);
7914 decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
7915 val, loc);
7918 Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
7919 if (decl_init != NULL)
7920 block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
7921 return block_stmt;
7924 // Export the variable
7926 void
7927 Variable::export_var(Export* exp, const Named_object* no) const
7929 go_assert(this->is_global_);
7930 exp->write_c_string("var ");
7931 if (no->package() != NULL)
7933 char buf[50];
7934 snprintf(buf, sizeof buf, "<p%d>", exp->package_index(no->package()));
7935 exp->write_c_string(buf);
7938 if (!Gogo::is_hidden_name(no->name()))
7939 exp->write_string(no->name());
7940 else
7942 exp->write_c_string(".");
7943 exp->write_string(Gogo::unpack_hidden_name(no->name()));
7946 exp->write_c_string(" ");
7947 exp->write_type(this->type());
7948 exp->write_c_string("\n");
7951 // Import a variable.
7953 bool
7954 Variable::import_var(Import* imp, std::string* pname, Package** ppkg,
7955 bool* pis_exported, Type** ptype)
7957 imp->require_c_string("var ");
7958 if (!Import::read_qualified_identifier(imp, pname, ppkg, pis_exported))
7960 go_error_at(imp->location(),
7961 "import error at %d: bad variable name in export data",
7962 imp->pos());
7963 return false;
7965 imp->require_c_string(" ");
7966 *ptype = imp->read_type();
7967 imp->require_semicolon_if_old_version();
7968 imp->require_c_string("\n");
7969 return true;
7972 // Convert a variable to the backend representation.
7974 Bvariable*
7975 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
7976 const Package* package, const std::string& name)
7978 if (this->backend_ == NULL)
7980 Backend* backend = gogo->backend();
7981 Type* type = this->type_;
7982 if (type->is_error_type()
7983 || (type->is_undefined()
7984 && (!this->is_global_ || package == NULL)))
7985 this->backend_ = backend->error_variable();
7986 else
7988 bool is_parameter = this->is_parameter_;
7989 if (this->is_receiver_ && type->points_to() == NULL)
7990 is_parameter = false;
7991 if (this->is_in_heap())
7993 is_parameter = false;
7994 type = Type::make_pointer_type(type);
7997 Btype* btype = type->get_backend(gogo);
7999 Bvariable* bvar;
8000 if (Map_type::is_zero_value(this))
8001 bvar = Map_type::backend_zero_value(gogo);
8002 else if (this->is_global_)
8004 Backend_name bname;
8005 gogo->global_var_backend_name(name, package, &bname);
8007 bool is_hidden = Gogo::is_hidden_name(name);
8008 // Hack to export runtime.writeBarrier. FIXME.
8009 // This is because go:linkname doesn't work on variables.
8010 if (gogo->compiling_runtime()
8011 && bname.name() == "runtime.writeBarrier")
8012 is_hidden = false;
8014 // If an inline body refers to this variable, then it
8015 // needs to be visible in the symbol table.
8016 if (this->is_referenced_by_inline_)
8017 is_hidden = false;
8019 // If this variable is in a different package, then it
8020 // can't be treated as a hidden symbol. This case can
8021 // arise when an inlined function refers to a
8022 // package-scope unexported variable.
8023 if (package != NULL)
8024 is_hidden = false;
8026 unsigned int flags = 0;
8027 if (this->is_address_taken_
8028 || this->is_non_escaping_address_taken_)
8029 flags |= Backend::variable_address_is_taken;
8030 if (package != NULL)
8031 flags |= Backend::variable_is_external;
8032 if (is_hidden)
8033 flags |= Backend::variable_is_hidden;
8034 if (this->in_unique_section_)
8035 flags |= Backend::variable_in_unique_section;
8037 // For some reason asm_name can't be the empty string
8038 // for global_variable, so we call asm_name rather than
8039 // optional_asm_name here. FIXME.
8041 bvar = backend->global_variable(bname.name(),
8042 bname.asm_name(),
8043 btype, flags,
8044 this->location_);
8046 else if (function == NULL)
8048 go_assert(saw_errors());
8049 bvar = backend->error_variable();
8051 else
8053 const std::string n = Gogo::unpack_hidden_name(name);
8054 Bfunction* bfunction = function->func_value()->get_decl();
8055 unsigned int flags = 0;
8056 if (this->is_non_escaping_address_taken_
8057 && !this->is_in_heap())
8058 flags |= Backend::variable_address_is_taken;
8059 if (this->is_closure())
8060 bvar = backend->static_chain_variable(bfunction, n, btype,
8061 flags, this->location_);
8062 else if (is_parameter)
8063 bvar = backend->parameter_variable(bfunction, n, btype,
8064 flags, this->location_);
8065 else
8067 Bvariable* bvar_decl = NULL;
8068 if (this->toplevel_decl_ != NULL)
8070 Translate_context context(gogo, NULL, NULL, NULL);
8071 bvar_decl = this->toplevel_decl_->temporary_statement()
8072 ->get_backend_variable(&context);
8074 bvar = backend->local_variable(bfunction, n, btype,
8075 bvar_decl, flags,
8076 this->location_);
8079 this->backend_ = bvar;
8082 return this->backend_;
8085 // Class Result_variable.
8087 // Convert a result variable to the backend representation.
8089 Bvariable*
8090 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
8091 const std::string& name)
8093 if (this->backend_ == NULL)
8095 Backend* backend = gogo->backend();
8096 Type* type = this->type_;
8097 if (type->is_error())
8098 this->backend_ = backend->error_variable();
8099 else
8101 if (this->is_in_heap())
8102 type = Type::make_pointer_type(type);
8103 Btype* btype = type->get_backend(gogo);
8104 Bfunction* bfunction = function->func_value()->get_decl();
8105 std::string n = Gogo::unpack_hidden_name(name);
8106 unsigned int flags = 0;
8107 if (this->is_non_escaping_address_taken_
8108 && !this->is_in_heap())
8109 flags |= Backend::variable_address_is_taken;
8110 this->backend_ = backend->local_variable(bfunction, n, btype,
8111 NULL, flags,
8112 this->location_);
8115 return this->backend_;
8118 // Class Named_constant.
8120 // Set the type of a named constant. This is only used to set the
8121 // type to an error type.
8123 void
8124 Named_constant::set_type(Type* t)
8126 go_assert(this->type_ == NULL || t->is_error_type());
8127 this->type_ = t;
8130 // Traverse the initializer expression.
8133 Named_constant::traverse_expression(Traverse* traverse)
8135 return Expression::traverse(&this->expr_, traverse);
8138 // Determine the type of the constant.
8140 void
8141 Named_constant::determine_type()
8143 if (this->type_ != NULL)
8145 Type_context context(this->type_, false);
8146 this->expr_->determine_type(&context);
8148 else
8150 // A constant may have an abstract type.
8151 Type_context context(NULL, true);
8152 this->expr_->determine_type(&context);
8153 this->type_ = this->expr_->type();
8154 go_assert(this->type_ != NULL);
8158 // Indicate that we found and reported an error for this constant.
8160 void
8161 Named_constant::set_error()
8163 this->type_ = Type::make_error_type();
8164 this->expr_ = Expression::make_error(this->location_);
8167 // Export a constant.
8169 void
8170 Named_constant::export_const(Export* exp, const std::string& name) const
8172 exp->write_c_string("const ");
8173 exp->write_string(name);
8174 exp->write_c_string(" ");
8175 if (!this->type_->is_abstract())
8177 exp->write_type(this->type_);
8178 exp->write_c_string(" ");
8180 exp->write_c_string("= ");
8182 Export_function_body efb(exp, 0);
8183 if (!this->type_->is_abstract())
8184 efb.set_type_context(this->type_);
8185 this->expr()->export_expression(&efb);
8186 exp->write_string(efb.body());
8188 exp->write_c_string("\n");
8191 // Import a constant.
8193 void
8194 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
8195 Expression** pexpr)
8197 imp->require_c_string("const ");
8198 *pname = imp->read_identifier();
8199 imp->require_c_string(" ");
8200 if (imp->peek_char() == '=')
8201 *ptype = NULL;
8202 else
8204 *ptype = imp->read_type();
8205 imp->require_c_string(" ");
8207 imp->require_c_string("= ");
8208 *pexpr = Expression::import_expression(imp, imp->location());
8209 imp->require_semicolon_if_old_version();
8210 imp->require_c_string("\n");
8213 // Get the backend representation.
8215 Bexpression*
8216 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
8218 if (this->bconst_ == NULL)
8220 Translate_context subcontext(gogo, NULL, NULL, NULL);
8221 Type* type = this->type();
8222 Location loc = this->location();
8224 Expression* const_ref = Expression::make_const_reference(const_no, loc);
8225 Bexpression* const_decl = const_ref->get_backend(&subcontext);
8226 if (type != NULL && type->is_numeric_type())
8228 Btype* btype = type->get_backend(gogo);
8229 std::string name;
8230 if (const_no->package() == NULL)
8231 name = gogo->pkgpath();
8232 else
8233 name = const_no->package()->pkgpath();
8234 name.push_back('.');
8235 name.append(Gogo::unpack_hidden_name(const_no->name()));
8236 const_decl =
8237 gogo->backend()->named_constant_expression(btype, name,
8238 const_decl, loc);
8240 this->bconst_ = const_decl;
8242 return this->bconst_;
8245 // Add a method.
8247 Named_object*
8248 Type_declaration::add_method(const std::string& name, Function* function)
8250 Named_object* ret = Named_object::make_function(name, NULL, function);
8251 this->methods_.push_back(ret);
8252 return ret;
8255 // Add a method declaration.
8257 Named_object*
8258 Type_declaration::add_method_declaration(const std::string& name,
8259 Package* package,
8260 Function_type* type,
8261 Location location)
8263 Named_object* ret = Named_object::make_function_declaration(name, package,
8264 type, location);
8265 this->methods_.push_back(ret);
8266 return ret;
8269 // Return whether any methods are defined.
8271 bool
8272 Type_declaration::has_methods() const
8274 return !this->methods_.empty();
8277 // Define methods for the real type.
8279 void
8280 Type_declaration::define_methods(Named_type* nt)
8282 if (this->methods_.empty())
8283 return;
8285 while (nt->is_alias())
8287 Type *t = nt->real_type()->forwarded();
8288 if (t->named_type() != NULL)
8289 nt = t->named_type();
8290 else if (t->forward_declaration_type() != NULL)
8292 Named_object* no = t->forward_declaration_type()->named_object();
8293 Type_declaration* td = no->type_declaration_value();
8294 td->methods_.insert(td->methods_.end(), this->methods_.begin(),
8295 this->methods_.end());
8296 this->methods_.clear();
8297 return;
8299 else
8301 for (std::vector<Named_object*>::const_iterator p =
8302 this->methods_.begin();
8303 p != this->methods_.end();
8304 ++p)
8305 go_error_at((*p)->location(),
8306 ("invalid receiver type "
8307 "(receiver must be a named type)"));
8308 return;
8312 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
8313 p != this->methods_.end();
8314 ++p)
8316 if ((*p)->is_function_declaration()
8317 || !(*p)->func_value()->is_sink())
8318 nt->add_existing_method(*p);
8322 // We are using the type. Return true if we should issue a warning.
8324 bool
8325 Type_declaration::using_type()
8327 bool ret = !this->issued_warning_;
8328 this->issued_warning_ = true;
8329 return ret;
8332 // Class Unknown_name.
8334 // Set the real named object.
8336 void
8337 Unknown_name::set_real_named_object(Named_object* no)
8339 go_assert(this->real_named_object_ == NULL);
8340 go_assert(!no->is_unknown());
8341 this->real_named_object_ = no;
8344 // Class Named_object.
8346 Named_object::Named_object(const std::string& name,
8347 const Package* package,
8348 Classification classification)
8349 : name_(name), package_(package), classification_(classification),
8350 is_redefinition_(false)
8352 if (Gogo::is_sink_name(name))
8353 go_assert(classification == NAMED_OBJECT_SINK);
8356 // Make an unknown name. This is used by the parser. The name must
8357 // be resolved later. Unknown names are only added in the current
8358 // package.
8360 Named_object*
8361 Named_object::make_unknown_name(const std::string& name,
8362 Location location)
8364 Named_object* named_object = new Named_object(name, NULL,
8365 NAMED_OBJECT_UNKNOWN);
8366 Unknown_name* value = new Unknown_name(location);
8367 named_object->u_.unknown_value = value;
8368 return named_object;
8371 // Make a constant.
8373 Named_object*
8374 Named_object::make_constant(const Typed_identifier& tid,
8375 const Package* package, Expression* expr,
8376 int iota_value)
8378 Named_object* named_object = new Named_object(tid.name(), package,
8379 NAMED_OBJECT_CONST);
8380 Named_constant* named_constant = new Named_constant(tid.type(), expr,
8381 iota_value,
8382 tid.location());
8383 named_object->u_.const_value = named_constant;
8384 return named_object;
8387 // Make a named type.
8389 Named_object*
8390 Named_object::make_type(const std::string& name, const Package* package,
8391 Type* type, Location location)
8393 Named_object* named_object = new Named_object(name, package,
8394 NAMED_OBJECT_TYPE);
8395 Named_type* named_type = Type::make_named_type(named_object, type, location);
8396 named_object->u_.type_value = named_type;
8397 return named_object;
8400 // Make a type declaration.
8402 Named_object*
8403 Named_object::make_type_declaration(const std::string& name,
8404 const Package* package,
8405 Location location)
8407 Named_object* named_object = new Named_object(name, package,
8408 NAMED_OBJECT_TYPE_DECLARATION);
8409 Type_declaration* type_declaration = new Type_declaration(location);
8410 named_object->u_.type_declaration = type_declaration;
8411 return named_object;
8414 // Make a variable.
8416 Named_object*
8417 Named_object::make_variable(const std::string& name, const Package* package,
8418 Variable* variable)
8420 Named_object* named_object = new Named_object(name, package,
8421 NAMED_OBJECT_VAR);
8422 named_object->u_.var_value = variable;
8423 return named_object;
8426 // Make a result variable.
8428 Named_object*
8429 Named_object::make_result_variable(const std::string& name,
8430 Result_variable* result)
8432 Named_object* named_object = new Named_object(name, NULL,
8433 NAMED_OBJECT_RESULT_VAR);
8434 named_object->u_.result_var_value = result;
8435 return named_object;
8438 // Make a sink. This is used for the special blank identifier _.
8440 Named_object*
8441 Named_object::make_sink()
8443 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
8446 // Make a named function.
8448 Named_object*
8449 Named_object::make_function(const std::string& name, const Package* package,
8450 Function* function)
8452 Named_object* named_object = new Named_object(name, package,
8453 NAMED_OBJECT_FUNC);
8454 named_object->u_.func_value = function;
8455 return named_object;
8458 // Make a function declaration.
8460 Named_object*
8461 Named_object::make_function_declaration(const std::string& name,
8462 const Package* package,
8463 Function_type* fntype,
8464 Location location)
8466 Named_object* named_object = new Named_object(name, package,
8467 NAMED_OBJECT_FUNC_DECLARATION);
8468 Function_declaration *func_decl = new Function_declaration(fntype, location);
8469 named_object->u_.func_declaration_value = func_decl;
8470 return named_object;
8473 // Make a package.
8475 Named_object*
8476 Named_object::make_package(const std::string& alias, Package* package)
8478 Named_object* named_object = new Named_object(alias, NULL,
8479 NAMED_OBJECT_PACKAGE);
8480 named_object->u_.package_value = package;
8481 return named_object;
8484 // Return the name to use in an error message.
8486 std::string
8487 Named_object::message_name() const
8489 if (this->package_ == NULL)
8490 return Gogo::message_name(this->name_);
8491 std::string ret;
8492 if (this->package_->has_package_name())
8493 ret = this->package_->package_name();
8494 else
8495 ret = this->package_->pkgpath();
8496 ret = Gogo::message_name(ret);
8497 ret += '.';
8498 ret += Gogo::message_name(this->name_);
8499 return ret;
8502 // Set the type when a declaration is defined.
8504 void
8505 Named_object::set_type_value(Named_type* named_type)
8507 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
8508 Type_declaration* td = this->u_.type_declaration;
8509 td->define_methods(named_type);
8510 unsigned int index;
8511 Named_object* in_function = td->in_function(&index);
8512 if (in_function != NULL)
8513 named_type->set_in_function(in_function, index);
8514 delete td;
8515 this->classification_ = NAMED_OBJECT_TYPE;
8516 this->u_.type_value = named_type;
8519 // Define a function which was previously declared.
8521 void
8522 Named_object::set_function_value(Function* function)
8524 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
8525 if (this->func_declaration_value()->has_descriptor())
8527 Expression* descriptor =
8528 this->func_declaration_value()->descriptor(NULL, NULL);
8529 function->set_descriptor(descriptor);
8531 this->classification_ = NAMED_OBJECT_FUNC;
8532 // FIXME: We should free the old value.
8533 this->u_.func_value = function;
8536 // Declare an unknown object as a type declaration.
8538 void
8539 Named_object::declare_as_type()
8541 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
8542 Unknown_name* unk = this->u_.unknown_value;
8543 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
8544 this->u_.type_declaration = new Type_declaration(unk->location());
8545 delete unk;
8548 // Return the location of a named object.
8550 Location
8551 Named_object::location() const
8553 switch (this->classification_)
8555 default:
8556 case NAMED_OBJECT_UNINITIALIZED:
8557 go_unreachable();
8559 case NAMED_OBJECT_ERRONEOUS:
8560 return Linemap::unknown_location();
8562 case NAMED_OBJECT_UNKNOWN:
8563 return this->unknown_value()->location();
8565 case NAMED_OBJECT_CONST:
8566 return this->const_value()->location();
8568 case NAMED_OBJECT_TYPE:
8569 return this->type_value()->location();
8571 case NAMED_OBJECT_TYPE_DECLARATION:
8572 return this->type_declaration_value()->location();
8574 case NAMED_OBJECT_VAR:
8575 return this->var_value()->location();
8577 case NAMED_OBJECT_RESULT_VAR:
8578 return this->result_var_value()->location();
8580 case NAMED_OBJECT_SINK:
8581 go_unreachable();
8583 case NAMED_OBJECT_FUNC:
8584 return this->func_value()->location();
8586 case NAMED_OBJECT_FUNC_DECLARATION:
8587 return this->func_declaration_value()->location();
8589 case NAMED_OBJECT_PACKAGE:
8590 return this->package_value()->location();
8594 // Traverse a Named_object.
8597 Named_object::traverse(Traverse* traverse, bool is_global)
8599 const unsigned int traverse_mask = traverse->traverse_mask();
8600 const unsigned int e_or_t = (Traverse::traverse_expressions
8601 | Traverse::traverse_types);
8602 const unsigned int e_or_t_or_s = (e_or_t
8603 | Traverse::traverse_statements);
8605 int t = TRAVERSE_CONTINUE;
8606 switch (this->classification_)
8608 case Named_object::NAMED_OBJECT_CONST:
8609 if ((traverse_mask & Traverse::traverse_constants) != 0)
8610 t = traverse->constant(this, is_global);
8611 if (t == TRAVERSE_CONTINUE
8612 && (traverse_mask & e_or_t) != 0)
8614 Type* tc = this->const_value()->type();
8615 if (tc != NULL)
8617 if (Type::traverse(tc, traverse) == TRAVERSE_EXIT)
8618 return TRAVERSE_EXIT;
8620 t = this->const_value()->traverse_expression(traverse);
8622 break;
8624 case Named_object::NAMED_OBJECT_VAR:
8625 case Named_object::NAMED_OBJECT_RESULT_VAR:
8626 if ((traverse_mask & Traverse::traverse_variables) != 0)
8627 t = traverse->variable(this);
8628 if (t == TRAVERSE_CONTINUE
8629 && (traverse_mask & e_or_t) != 0)
8631 if (this->is_result_variable() || this->var_value()->has_type())
8633 Type* tv = (this->is_variable()
8634 ? this->var_value()->type()
8635 : this->result_var_value()->type());
8636 if (tv != NULL)
8638 if (Type::traverse(tv, traverse) == TRAVERSE_EXIT)
8639 return TRAVERSE_EXIT;
8643 if (t == TRAVERSE_CONTINUE
8644 && (traverse_mask & e_or_t_or_s) != 0
8645 && this->is_variable())
8646 t = this->var_value()->traverse_expression(traverse,
8647 traverse_mask);
8648 break;
8650 case Named_object::NAMED_OBJECT_FUNC:
8651 if ((traverse_mask & Traverse::traverse_functions) != 0)
8652 t = traverse->function(this);
8653 if (t == TRAVERSE_CONTINUE
8654 && (traverse_mask
8655 & (Traverse::traverse_variables
8656 | Traverse::traverse_constants
8657 | Traverse::traverse_functions
8658 | Traverse::traverse_blocks
8659 | Traverse::traverse_statements
8660 | Traverse::traverse_expressions
8661 | Traverse::traverse_types)) != 0)
8662 t = this->func_value()->traverse(traverse);
8663 break;
8665 case Named_object::NAMED_OBJECT_TYPE:
8666 if ((traverse_mask & e_or_t) != 0)
8667 t = Type::traverse(this->type_value(), traverse);
8668 break;
8670 case Named_object::NAMED_OBJECT_PACKAGE:
8671 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8672 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8673 case Named_object::NAMED_OBJECT_UNKNOWN:
8674 case Named_object::NAMED_OBJECT_ERRONEOUS:
8675 break;
8677 case Named_object::NAMED_OBJECT_SINK:
8678 go_unreachable();
8680 default:
8681 go_unreachable();
8684 return t;
8687 // Export a named object.
8689 void
8690 Named_object::export_named_object(Export* exp) const
8692 switch (this->classification_)
8694 default:
8695 case NAMED_OBJECT_UNINITIALIZED:
8696 case NAMED_OBJECT_UNKNOWN:
8697 go_unreachable();
8699 case NAMED_OBJECT_ERRONEOUS:
8700 break;
8702 case NAMED_OBJECT_CONST:
8703 this->const_value()->export_const(exp, this->name_);
8704 break;
8706 case NAMED_OBJECT_TYPE:
8707 // Types are handled by export::write_types.
8708 go_unreachable();
8710 case NAMED_OBJECT_TYPE_DECLARATION:
8711 go_error_at(this->type_declaration_value()->location(),
8712 "attempt to export %<%s%> which was declared but not defined",
8713 this->message_name().c_str());
8714 break;
8716 case NAMED_OBJECT_FUNC_DECLARATION:
8717 this->func_declaration_value()->export_func(exp, this);
8718 break;
8720 case NAMED_OBJECT_VAR:
8721 this->var_value()->export_var(exp, this);
8722 break;
8724 case NAMED_OBJECT_RESULT_VAR:
8725 case NAMED_OBJECT_SINK:
8726 go_unreachable();
8728 case NAMED_OBJECT_FUNC:
8729 this->func_value()->export_func(exp, this);
8730 break;
8734 // Convert a variable to the backend representation.
8736 Bvariable*
8737 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
8739 if (this->classification_ == NAMED_OBJECT_VAR)
8740 return this->var_value()->get_backend_variable(gogo, function,
8741 this->package_, this->name_);
8742 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
8743 return this->result_var_value()->get_backend_variable(gogo, function,
8744 this->name_);
8745 else
8746 go_unreachable();
8749 void
8750 debug_go_named_object(Named_object* no)
8752 if (no == NULL)
8754 std::cerr << "<null>";
8755 return;
8757 std::cerr << "'" << no->name() << "': ";
8758 const char *tag;
8759 switch (no->classification())
8761 case Named_object::NAMED_OBJECT_UNINITIALIZED:
8762 tag = "uninitialized";
8763 break;
8764 case Named_object::NAMED_OBJECT_ERRONEOUS:
8765 tag = "<error>";
8766 break;
8767 case Named_object::NAMED_OBJECT_UNKNOWN:
8768 tag = "<unknown>";
8769 break;
8770 case Named_object::NAMED_OBJECT_CONST:
8771 tag = "constant";
8772 break;
8773 case Named_object::NAMED_OBJECT_TYPE:
8774 tag = "type";
8775 break;
8776 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8777 tag = "type_decl";
8778 break;
8779 case Named_object::NAMED_OBJECT_VAR:
8780 tag = "var";
8781 break;
8782 case Named_object::NAMED_OBJECT_RESULT_VAR:
8783 tag = "result_var";
8784 break;
8785 case Named_object::NAMED_OBJECT_SINK:
8786 tag = "<sink>";
8787 break;
8788 case Named_object::NAMED_OBJECT_FUNC:
8789 tag = "func";
8790 break;
8791 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8792 tag = "func_decl";
8793 break;
8794 case Named_object::NAMED_OBJECT_PACKAGE:
8795 tag = "package";
8796 break;
8797 default:
8798 tag = "<unknown named object classification>";
8799 break;
8801 std::cerr << tag << "\n";
8804 // Get the backend representation for this named object.
8806 void
8807 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
8808 std::vector<Btype*>& type_decls,
8809 std::vector<Bfunction*>& func_decls)
8811 // If this is a definition, avoid trying to get the backend
8812 // representation, as that can crash.
8813 if (this->is_redefinition_)
8815 go_assert(saw_errors());
8816 return;
8819 switch (this->classification_)
8821 case NAMED_OBJECT_CONST:
8822 if (!Gogo::is_erroneous_name(this->name_))
8823 const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
8824 break;
8826 case NAMED_OBJECT_TYPE:
8828 Named_type* named_type = this->u_.type_value;
8830 // No need to do anything for aliases-- whatever has to be done
8831 // can be done for the alias target.
8832 if (named_type->is_alias())
8833 break;
8835 if (!Gogo::is_erroneous_name(this->name_))
8836 type_decls.push_back(named_type->get_backend(gogo));
8838 // We need to produce a type descriptor for every named
8839 // type, and for a pointer to every named type, since
8840 // other files or packages might refer to them. We need
8841 // to do this even for hidden types, because they might
8842 // still be returned by some function. Simply calling the
8843 // type_descriptor method is enough to create the type
8844 // descriptor, even though we don't do anything with it.
8845 if (this->package_ == NULL && !saw_errors())
8847 named_type->
8848 type_descriptor_pointer(gogo, Linemap::predeclared_location());
8849 Type* pn = Type::make_pointer_type(named_type);
8850 pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
8851 if (named_type->in_heap())
8853 named_type->gc_symbol_pointer(gogo);
8854 pn->gc_symbol_pointer(gogo);
8858 break;
8860 case NAMED_OBJECT_TYPE_DECLARATION:
8861 go_error_at(Linemap::unknown_location(),
8862 "reference to undefined type %qs",
8863 this->message_name().c_str());
8864 return;
8866 case NAMED_OBJECT_VAR:
8867 case NAMED_OBJECT_RESULT_VAR:
8868 case NAMED_OBJECT_SINK:
8869 go_unreachable();
8871 case NAMED_OBJECT_FUNC:
8873 Function* func = this->u_.func_value;
8874 if (!Gogo::is_erroneous_name(this->name_))
8875 func_decls.push_back(func->get_or_make_decl(gogo, this));
8877 if (func->block() != NULL)
8878 func->build(gogo, this);
8880 break;
8882 case NAMED_OBJECT_ERRONEOUS:
8883 break;
8885 default:
8886 go_unreachable();
8890 // Class Bindings.
8892 Bindings::Bindings(Bindings* enclosing)
8893 : enclosing_(enclosing), named_objects_(), bindings_()
8897 // Clear imports.
8899 void
8900 Bindings::clear_file_scope(Gogo* gogo)
8902 Contour::iterator p = this->bindings_.begin();
8903 while (p != this->bindings_.end())
8905 bool keep;
8906 if (p->second->package() != NULL)
8907 keep = false;
8908 else if (p->second->is_package())
8909 keep = false;
8910 else if (p->second->is_function()
8911 && !p->second->func_value()->type()->is_method()
8912 && Gogo::unpack_hidden_name(p->second->name()) == "init")
8913 keep = false;
8914 else
8915 keep = true;
8917 if (keep)
8918 ++p;
8919 else
8921 gogo->add_file_block_name(p->second->name(), p->second->location());
8922 p = this->bindings_.erase(p);
8927 // Look up a symbol.
8929 Named_object*
8930 Bindings::lookup(const std::string& name) const
8932 Contour::const_iterator p = this->bindings_.find(name);
8933 if (p != this->bindings_.end())
8934 return p->second->resolve();
8935 else if (this->enclosing_ != NULL)
8936 return this->enclosing_->lookup(name);
8937 else
8938 return NULL;
8941 // Look up a symbol locally.
8943 Named_object*
8944 Bindings::lookup_local(const std::string& name) const
8946 Contour::const_iterator p = this->bindings_.find(name);
8947 if (p == this->bindings_.end())
8948 return NULL;
8949 return p->second;
8952 // Remove an object from a set of bindings. This is used for a
8953 // special case in thunks for functions which call recover.
8955 void
8956 Bindings::remove_binding(Named_object* no)
8958 Contour::iterator pb = this->bindings_.find(no->name());
8959 go_assert(pb != this->bindings_.end());
8960 this->bindings_.erase(pb);
8961 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
8962 pn != this->named_objects_.end();
8963 ++pn)
8965 if (*pn == no)
8967 this->named_objects_.erase(pn);
8968 return;
8971 go_unreachable();
8974 // Add a method to the list of objects. This is not added to the
8975 // lookup table. This is so that we have a single list of objects
8976 // declared at the top level, which we walk through when it's time to
8977 // convert to trees.
8979 void
8980 Bindings::add_method(Named_object* method)
8982 this->named_objects_.push_back(method);
8985 // Add a generic Named_object to a Contour.
8987 Named_object*
8988 Bindings::add_named_object_to_contour(Contour* contour,
8989 Named_object* named_object)
8991 go_assert(named_object == named_object->resolve());
8992 const std::string& name(named_object->name());
8993 go_assert(!Gogo::is_sink_name(name));
8995 std::pair<Contour::iterator, bool> ins =
8996 contour->insert(std::make_pair(name, named_object));
8997 if (!ins.second)
8999 // The name was already there.
9000 if (named_object->package() != NULL
9001 && ins.first->second->package() == named_object->package()
9002 && (ins.first->second->classification()
9003 == named_object->classification()))
9005 // This is a second import of the same object.
9006 return ins.first->second;
9008 ins.first->second = this->new_definition(ins.first->second,
9009 named_object);
9010 return ins.first->second;
9012 else
9014 // Don't push declarations on the list. We push them on when
9015 // and if we find the definitions. That way we genericize the
9016 // functions in order.
9017 if (!named_object->is_type_declaration()
9018 && !named_object->is_function_declaration()
9019 && !named_object->is_unknown())
9020 this->named_objects_.push_back(named_object);
9021 return named_object;
9025 // We had an existing named object OLD_OBJECT, and we've seen a new
9026 // one NEW_OBJECT with the same name. FIXME: This does not free the
9027 // new object when we don't need it.
9029 Named_object*
9030 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
9032 if (new_object->is_erroneous() && !old_object->is_erroneous())
9033 return new_object;
9035 std::string reason;
9036 switch (old_object->classification())
9038 default:
9039 case Named_object::NAMED_OBJECT_UNINITIALIZED:
9040 go_unreachable();
9042 case Named_object::NAMED_OBJECT_ERRONEOUS:
9043 return old_object;
9045 case Named_object::NAMED_OBJECT_UNKNOWN:
9047 Named_object* real = old_object->unknown_value()->real_named_object();
9048 if (real != NULL)
9049 return this->new_definition(real, new_object);
9050 go_assert(!new_object->is_unknown());
9051 old_object->unknown_value()->set_real_named_object(new_object);
9052 if (!new_object->is_type_declaration()
9053 && !new_object->is_function_declaration())
9054 this->named_objects_.push_back(new_object);
9055 return new_object;
9058 case Named_object::NAMED_OBJECT_CONST:
9059 break;
9061 case Named_object::NAMED_OBJECT_TYPE:
9062 if (new_object->is_type_declaration())
9063 return old_object;
9064 break;
9066 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
9067 if (new_object->is_type_declaration())
9068 return old_object;
9069 if (new_object->is_type())
9071 old_object->set_type_value(new_object->type_value());
9072 new_object->type_value()->set_named_object(old_object);
9073 this->named_objects_.push_back(old_object);
9074 return old_object;
9076 break;
9078 case Named_object::NAMED_OBJECT_VAR:
9079 case Named_object::NAMED_OBJECT_RESULT_VAR:
9080 // We have already given an error in the parser for cases where
9081 // one parameter or result variable redeclares another one.
9082 if ((new_object->is_variable()
9083 && new_object->var_value()->is_parameter())
9084 || new_object->is_result_variable())
9085 return old_object;
9086 break;
9088 case Named_object::NAMED_OBJECT_SINK:
9089 go_unreachable();
9091 case Named_object::NAMED_OBJECT_FUNC:
9092 break;
9094 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
9096 // We declare the hash and equality functions before defining
9097 // them, because we sometimes see that we need the declaration
9098 // while we are in the middle of a different function.
9100 // We declare the main function before the user defines it, to
9101 // give better error messages.
9103 // We declare inline functions before we define them, as we
9104 // only define them if we need them.
9105 if (new_object->is_function()
9106 && ((Linemap::is_predeclared_location(old_object->location())
9107 && Linemap::is_predeclared_location(new_object->location()))
9108 || (Gogo::unpack_hidden_name(old_object->name()) == "main"
9109 && Linemap::is_unknown_location(old_object->location()))
9110 || (new_object->package() != NULL
9111 && old_object->func_declaration_value()->has_imported_body()
9112 && new_object->func_value()->is_inline_only())))
9114 Function_type* old_type =
9115 old_object->func_declaration_value()->type();
9116 Function_type* new_type = new_object->func_value()->type();
9117 if (old_type->is_valid_redeclaration(new_type, &reason))
9119 Function_declaration* fd =
9120 old_object->func_declaration_value();
9121 go_assert(fd->asm_name().empty());
9122 old_object->set_function_value(new_object->func_value());
9123 this->named_objects_.push_back(old_object);
9124 return old_object;
9128 break;
9130 case Named_object::NAMED_OBJECT_PACKAGE:
9131 break;
9134 std::string n = old_object->message_name();
9135 if (reason.empty())
9136 go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
9137 else
9138 go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
9139 reason.c_str());
9140 old_object->set_is_redefinition();
9141 new_object->set_is_redefinition();
9143 if (!Linemap::is_unknown_location(old_object->location())
9144 && !Linemap::is_predeclared_location(old_object->location()))
9145 go_inform(old_object->location(), "previous definition of %qs was here",
9146 n.c_str());
9148 return old_object;
9151 // Add a named type.
9153 Named_object*
9154 Bindings::add_named_type(Named_type* named_type)
9156 return this->add_named_object(named_type->named_object());
9159 // Add a function.
9161 Named_object*
9162 Bindings::add_function(const std::string& name, const Package* package,
9163 Function* function)
9165 return this->add_named_object(Named_object::make_function(name, package,
9166 function));
9169 // Add a function declaration.
9171 Named_object*
9172 Bindings::add_function_declaration(const std::string& name,
9173 const Package* package,
9174 Function_type* type,
9175 Location location)
9177 Named_object* no = Named_object::make_function_declaration(name, package,
9178 type, location);
9179 return this->add_named_object(no);
9182 // Define a type which was previously declared.
9184 void
9185 Bindings::define_type(Named_object* no, Named_type* type)
9187 no->set_type_value(type);
9188 this->named_objects_.push_back(no);
9191 // Mark all local variables as used. This is used for some types of
9192 // parse error.
9194 void
9195 Bindings::mark_locals_used()
9197 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
9198 p != this->named_objects_.end();
9199 ++p)
9200 if ((*p)->is_variable())
9201 (*p)->var_value()->set_is_used();
9204 // Traverse bindings.
9207 Bindings::traverse(Traverse* traverse, bool is_global)
9209 unsigned int traverse_mask = traverse->traverse_mask();
9211 // We don't use an iterator because we permit the traversal to add
9212 // new global objects.
9213 const unsigned int e_or_t = (Traverse::traverse_expressions
9214 | Traverse::traverse_types);
9215 for (size_t i = 0; i < this->named_objects_.size(); ++i)
9217 Named_object* p = this->named_objects_[i];
9218 if (p->traverse(traverse, is_global) == TRAVERSE_EXIT)
9219 return TRAVERSE_EXIT;
9222 // If we need to traverse types, check the function declarations,
9223 // which have types. Also check any methods of a type declaration.
9224 if ((traverse_mask & e_or_t) != 0)
9226 for (Bindings::const_declarations_iterator p =
9227 this->begin_declarations();
9228 p != this->end_declarations();
9229 ++p)
9231 if (p->second->is_function_declaration())
9233 if (Type::traverse(p->second->func_declaration_value()->type(),
9234 traverse)
9235 == TRAVERSE_EXIT)
9236 return TRAVERSE_EXIT;
9238 else if (p->second->is_type_declaration())
9240 const std::vector<Named_object*>* methods =
9241 p->second->type_declaration_value()->methods();
9242 for (std::vector<Named_object*>::const_iterator pm =
9243 methods->begin();
9244 pm != methods->end();
9245 pm++)
9247 Named_object* no = *pm;
9248 Type *t;
9249 if (no->is_function())
9250 t = no->func_value()->type();
9251 else if (no->is_function_declaration())
9252 t = no->func_declaration_value()->type();
9253 else
9254 continue;
9255 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
9256 return TRAVERSE_EXIT;
9262 // Traverse function declarations when needed.
9263 if ((traverse_mask & Traverse::traverse_func_declarations) != 0)
9265 for (Bindings::const_declarations_iterator p = this->begin_declarations();
9266 p != this->end_declarations();
9267 ++p)
9269 if (p->second->is_function_declaration())
9271 if (traverse->function_declaration(p->second) == TRAVERSE_EXIT)
9272 return TRAVERSE_EXIT;
9277 return TRAVERSE_CONTINUE;
9280 void
9281 Bindings::debug_dump()
9283 std::set<Named_object*> defs;
9284 for (size_t i = 0; i < this->named_objects_.size(); ++i)
9285 defs.insert(this->named_objects_[i]);
9286 for (Contour::iterator p = this->bindings_.begin();
9287 p != this->bindings_.end();
9288 ++p)
9290 const char* tag = " ";
9291 if (defs.find(p->second) != defs.end())
9292 tag = "* ";
9293 std::cerr << tag;
9294 debug_go_named_object(p->second);
9298 void
9299 debug_go_bindings(Bindings* bindings)
9301 if (bindings != NULL)
9302 bindings->debug_dump();
9305 // Class Label.
9307 // Clear any references to this label.
9309 void
9310 Label::clear_refs()
9312 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
9313 p != this->refs_.end();
9314 ++p)
9315 delete *p;
9316 this->refs_.clear();
9319 // Get the backend representation for a label.
9321 Blabel*
9322 Label::get_backend_label(Translate_context* context)
9324 if (this->blabel_ == NULL)
9326 Function* function = context->function()->func_value();
9327 Bfunction* bfunction = function->get_decl();
9328 this->blabel_ = context->backend()->label(bfunction, this->name_,
9329 this->location_);
9331 return this->blabel_;
9334 // Return an expression for the address of this label.
9336 Bexpression*
9337 Label::get_addr(Translate_context* context, Location location)
9339 Blabel* label = this->get_backend_label(context);
9340 return context->backend()->label_address(label, location);
9343 // Return the dummy label that represents any instance of the blank label.
9345 Label*
9346 Label::create_dummy_label()
9348 static Label* dummy_label;
9349 if (dummy_label == NULL)
9351 dummy_label = new Label("_");
9352 dummy_label->set_is_used();
9354 return dummy_label;
9357 // Class Unnamed_label.
9359 // Get the backend representation for an unnamed label.
9361 Blabel*
9362 Unnamed_label::get_blabel(Translate_context* context)
9364 if (this->blabel_ == NULL)
9366 Function* function = context->function()->func_value();
9367 Bfunction* bfunction = function->get_decl();
9368 this->blabel_ = context->backend()->label(bfunction, "",
9369 this->location_);
9371 return this->blabel_;
9374 // Return a statement which defines this unnamed label.
9376 Bstatement*
9377 Unnamed_label::get_definition(Translate_context* context)
9379 Blabel* blabel = this->get_blabel(context);
9380 return context->backend()->label_definition_statement(blabel);
9383 // Return a goto statement to this unnamed label.
9385 Bstatement*
9386 Unnamed_label::get_goto(Translate_context* context, Location location)
9388 Blabel* blabel = this->get_blabel(context);
9389 return context->backend()->goto_statement(blabel, location);
9392 // Class Package.
9394 Package::Package(const std::string& pkgpath,
9395 const std::string& pkgpath_symbol, Location location)
9396 : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
9397 package_name_(), bindings_(new Bindings(NULL)),
9398 location_(location)
9400 go_assert(!pkgpath.empty());
9403 // Set the package name.
9405 void
9406 Package::set_package_name(const std::string& package_name, Location location)
9408 go_assert(!package_name.empty());
9409 if (this->package_name_.empty())
9410 this->package_name_ = package_name;
9411 else if (this->package_name_ != package_name)
9412 go_error_at(location,
9413 ("saw two different packages with "
9414 "the same package path %s: %s, %s"),
9415 this->pkgpath_.c_str(), this->package_name_.c_str(),
9416 package_name.c_str());
9419 // Return the pkgpath symbol, which is a prefix for symbols defined in
9420 // this package.
9422 std::string
9423 Package::pkgpath_symbol() const
9425 if (this->pkgpath_symbol_.empty())
9426 return Gogo::pkgpath_for_symbol(this->pkgpath_);
9427 return this->pkgpath_symbol_;
9430 // Set the package path symbol.
9432 void
9433 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
9435 go_assert(!pkgpath_symbol.empty());
9436 if (this->pkgpath_symbol_.empty())
9437 this->pkgpath_symbol_ = pkgpath_symbol;
9438 else
9439 go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
9442 // Note that symbol from this package was and qualified by ALIAS.
9444 void
9445 Package::note_usage(const std::string& alias) const
9447 Aliases::const_iterator p = this->aliases_.find(alias);
9448 go_assert(p != this->aliases_.end());
9449 p->second->note_usage();
9452 // Forget a given usage. If forgetting this usage means this package becomes
9453 // unused, report that error.
9455 void
9456 Package::forget_usage(Expression* usage) const
9458 if (this->fake_uses_.empty())
9459 return;
9461 std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
9462 go_assert(p != this->fake_uses_.end());
9463 this->fake_uses_.erase(p);
9465 if (this->fake_uses_.empty())
9466 go_error_at(this->location(), "imported and not used: %s",
9467 Gogo::message_name(this->package_name()).c_str());
9470 // Clear the used field for the next file. If the only usages of this package
9471 // are possibly fake, keep the fake usages for lowering.
9473 void
9474 Package::clear_used()
9476 std::string dot_alias = "." + this->package_name();
9477 Aliases::const_iterator p = this->aliases_.find(dot_alias);
9478 if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
9479 this->fake_uses_.clear();
9481 this->aliases_.clear();
9484 Package_alias*
9485 Package::add_alias(const std::string& alias, Location location)
9487 Aliases::const_iterator p = this->aliases_.find(alias);
9488 if (p == this->aliases_.end())
9490 std::pair<Aliases::iterator, bool> ret;
9491 ret = this->aliases_.insert(std::make_pair(alias,
9492 new Package_alias(location)));
9493 p = ret.first;
9495 return p->second;
9498 // Determine types of constants. Everything else in a package
9499 // (variables, function declarations) should already have a fixed
9500 // type. Constants may have abstract types.
9502 void
9503 Package::determine_types()
9505 Bindings* bindings = this->bindings_;
9506 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
9507 p != bindings->end_definitions();
9508 ++p)
9510 if ((*p)->is_const())
9511 (*p)->const_value()->determine_type();
9515 // Class Traverse.
9517 // Destructor.
9519 Traverse::~Traverse()
9521 if (this->types_seen_ != NULL)
9522 delete this->types_seen_;
9523 if (this->expressions_seen_ != NULL)
9524 delete this->expressions_seen_;
9527 // Record that we are looking at a type, and return true if we have
9528 // already seen it.
9530 bool
9531 Traverse::remember_type(const Type* type)
9533 if (type->is_error_type())
9534 return true;
9535 go_assert((this->traverse_mask() & traverse_types) != 0
9536 || (this->traverse_mask() & traverse_expressions) != 0);
9537 // We mostly only have to remember named types. But it turns out
9538 // that an interface type can refer to itself without using a name
9539 // by relying on interface inheritance, as in
9541 // type I interface { F() interface{I} }
9543 // Similarly it is possible for array types to refer to themselves
9544 // without a name, e.g.
9546 // var x [uintptr(unsafe.Sizeof(&x))]byte
9548 if (type->classification() != Type::TYPE_NAMED
9549 && type->classification() != Type::TYPE_ARRAY
9550 && type->classification() != Type::TYPE_INTERFACE)
9551 return false;
9552 if (this->types_seen_ == NULL)
9553 this->types_seen_ = new Types_seen();
9554 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
9555 return !ins.second;
9558 // Record that we are looking at an expression, and return true if we
9559 // have already seen it. NB: this routine used to assert if the traverse
9560 // mask did not include expressions/types -- this is no longer the case,
9561 // since it can be useful to remember specific expressions during
9562 // walks that only cover statements.
9564 bool
9565 Traverse::remember_expression(const Expression* expression)
9567 if (this->expressions_seen_ == NULL)
9568 this->expressions_seen_ = new Expressions_seen();
9569 std::pair<Expressions_seen::iterator, bool> ins =
9570 this->expressions_seen_->insert(expression);
9571 return !ins.second;
9574 // The default versions of these functions should never be called: the
9575 // traversal mask indicates which functions may be called.
9578 Traverse::variable(Named_object*)
9580 go_unreachable();
9584 Traverse::constant(Named_object*, bool)
9586 go_unreachable();
9590 Traverse::function(Named_object*)
9592 go_unreachable();
9596 Traverse::block(Block*)
9598 go_unreachable();
9602 Traverse::statement(Block*, size_t*, Statement*)
9604 go_unreachable();
9608 Traverse::expression(Expression**)
9610 go_unreachable();
9614 Traverse::type(Type*)
9616 go_unreachable();
9620 Traverse::function_declaration(Named_object*)
9622 go_unreachable();
9625 // Class Statement_inserter.
9627 void
9628 Statement_inserter::insert(Statement* s)
9630 if (this->statements_added_ != NULL)
9631 this->statements_added_->insert(s);
9633 if (this->block_ != NULL)
9635 go_assert(this->pindex_ != NULL);
9636 this->block_->insert_statement_before(*this->pindex_, s);
9637 ++*this->pindex_;
9639 else if (this->var_ != NULL)
9640 this->var_->add_preinit_statement(this->gogo_, s);
9641 else
9642 go_assert(saw_errors());