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.
11 #include "filenames.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
17 #include "go-optimize.h"
20 #include "statements.h"
21 #include "expressions.h"
30 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
35 globals_(new Bindings(NULL
)),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
40 current_file_imported_embed_(false),
51 pkgpath_from_option_(false),
52 prefix_from_option_(false),
53 relative_import_path_(),
59 check_divide_by_zero_(true),
60 check_divide_overflow_(true),
61 compiling_runtime_(false),
62 debug_escape_level_(0),
63 debug_optimization_(false),
64 nil_check_size_threshold_(4096),
68 specific_type_functions_(),
69 specific_type_functions_are_written_(false),
70 named_types_are_converted_(false),
74 imported_inlinable_functions_(),
75 imported_inline_functions_()
77 const Location loc
= Linemap::predeclared_location();
79 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
80 RUNTIME_TYPE_KIND_UINT8
);
81 this->add_named_type(uint8_type
);
82 this->add_named_type(Type::make_integer_type("uint16", true, 16,
83 RUNTIME_TYPE_KIND_UINT16
));
84 this->add_named_type(Type::make_integer_type("uint32", true, 32,
85 RUNTIME_TYPE_KIND_UINT32
));
86 this->add_named_type(Type::make_integer_type("uint64", true, 64,
87 RUNTIME_TYPE_KIND_UINT64
));
89 this->add_named_type(Type::make_integer_type("int8", false, 8,
90 RUNTIME_TYPE_KIND_INT8
));
91 this->add_named_type(Type::make_integer_type("int16", false, 16,
92 RUNTIME_TYPE_KIND_INT16
));
93 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
94 RUNTIME_TYPE_KIND_INT32
);
95 this->add_named_type(int32_type
);
96 this->add_named_type(Type::make_integer_type("int64", false, 64,
97 RUNTIME_TYPE_KIND_INT64
));
99 this->add_named_type(Type::make_float_type("float32", 32,
100 RUNTIME_TYPE_KIND_FLOAT32
));
101 this->add_named_type(Type::make_float_type("float64", 64,
102 RUNTIME_TYPE_KIND_FLOAT64
));
104 this->add_named_type(Type::make_complex_type("complex64", 64,
105 RUNTIME_TYPE_KIND_COMPLEX64
));
106 this->add_named_type(Type::make_complex_type("complex128", 128,
107 RUNTIME_TYPE_KIND_COMPLEX128
));
109 int int_type_size
= pointer_size
;
110 if (int_type_size
< 32)
112 this->add_named_type(Type::make_integer_type("uint", true,
114 RUNTIME_TYPE_KIND_UINT
));
115 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
116 RUNTIME_TYPE_KIND_INT
);
117 this->add_named_type(int_type
);
119 this->add_named_type(Type::make_integer_type("uintptr", true,
121 RUNTIME_TYPE_KIND_UINTPTR
));
123 // "byte" is an alias for "uint8".
124 uint8_type
->integer_type()->set_is_byte();
125 this->add_named_type(Type::make_integer_type_alias("byte", uint8_type
));
127 // "rune" is an alias for "int32".
128 int32_type
->integer_type()->set_is_rune();
129 this->add_named_type(Type::make_integer_type_alias("rune", int32_type
));
131 this->add_named_type(Type::make_named_bool_type());
133 this->add_named_type(Type::make_named_string_type());
135 // "error" is interface { Error() string }.
137 Typed_identifier_list
*methods
= new Typed_identifier_list
;
138 Typed_identifier_list
*results
= new Typed_identifier_list
;
139 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
140 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
141 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
142 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
143 error_iface
->finalize_methods();
144 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
145 this->add_named_type(error_type
);
148 // "any" is an alias for the empty interface type.
150 Type
* empty
= Type::make_empty_interface_type(loc
);
151 Named_object
* no
= Named_object::make_type("any", NULL
, empty
, loc
);
152 Named_type
* nt
= no
->type_value();
154 this->add_named_type(nt
);
157 this->globals_
->add_constant(Typed_identifier("true",
158 Type::make_boolean_type(),
161 Expression::make_boolean(true, loc
),
163 this->globals_
->add_constant(Typed_identifier("false",
164 Type::make_boolean_type(),
167 Expression::make_boolean(false, loc
),
170 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
173 Expression::make_nil(loc
),
176 Type
* abstract_int_type
= Type::make_abstract_integer_type();
177 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
180 Expression::make_iota(),
183 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
184 new_type
->set_is_varargs();
185 new_type
->set_is_builtin();
186 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
188 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
189 make_type
->set_is_varargs();
190 make_type
->set_is_builtin();
191 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
193 Typed_identifier_list
* len_result
= new Typed_identifier_list();
194 len_result
->push_back(Typed_identifier("", int_type
, loc
));
195 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
197 len_type
->set_is_builtin();
198 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
200 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
201 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
202 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
204 cap_type
->set_is_builtin();
205 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
207 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
208 print_type
->set_is_varargs();
209 print_type
->set_is_builtin();
210 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
212 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
213 print_type
->set_is_varargs();
214 print_type
->set_is_builtin();
215 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
217 Type
*empty
= Type::make_empty_interface_type(loc
);
218 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
219 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
220 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
222 panic_type
->set_is_builtin();
223 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
225 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
226 recover_result
->push_back(Typed_identifier("", empty
, loc
));
227 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
230 recover_type
->set_is_builtin();
231 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
233 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
234 close_type
->set_is_varargs();
235 close_type
->set_is_builtin();
236 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
238 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
239 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
240 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
242 copy_type
->set_is_varargs();
243 copy_type
->set_is_builtin();
244 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
246 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
247 append_type
->set_is_varargs();
248 append_type
->set_is_builtin();
249 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
251 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
252 complex_type
->set_is_varargs();
253 complex_type
->set_is_builtin();
254 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
256 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
257 real_type
->set_is_varargs();
258 real_type
->set_is_builtin();
259 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
261 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
262 imag_type
->set_is_varargs();
263 imag_type
->set_is_builtin();
264 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
266 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
267 delete_type
->set_is_varargs();
268 delete_type
->set_is_builtin();
269 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
273 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
275 go_assert(!pkgpath
.empty());
276 return go_encode_id(pkgpath
);
279 // Return a hash code for a string, given a starting hash.
282 Gogo::hash_string(const std::string
& s
, unsigned int h
)
284 const char* p
= s
.data();
285 size_t len
= s
.length();
286 for (; len
> 0; --len
)
294 // Get the package path to use for type reflection data. This should
295 // ideally be unique across the entire link.
298 Gogo::pkgpath() const
300 go_assert(this->pkgpath_set_
);
301 return this->pkgpath_
;
304 // Set the package path from the -fgo-pkgpath command line option.
307 Gogo::set_pkgpath(const std::string
& arg
)
309 go_assert(!this->pkgpath_set_
);
310 this->pkgpath_
= arg
;
311 this->pkgpath_set_
= true;
312 this->pkgpath_from_option_
= true;
315 // Get the package path to use for symbol names.
318 Gogo::pkgpath_symbol() const
320 go_assert(this->pkgpath_set_
);
321 return this->pkgpath_symbol_
;
324 // Set the unique prefix to use to determine the package path, from
325 // the -fgo-prefix command line option.
328 Gogo::set_prefix(const std::string
& arg
)
330 go_assert(!this->prefix_from_option_
);
332 this->prefix_from_option_
= true;
335 // Munge name for use in an error message.
338 Gogo::message_name(const std::string
& name
)
340 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
343 // Get the package name.
346 Gogo::package_name() const
348 go_assert(this->package_
!= NULL
);
349 return this->package_
->package_name();
352 // Set the package name.
355 Gogo::set_package_name(const std::string
& package_name
,
358 if (this->package_
!= NULL
)
360 if (this->package_
->package_name() != package_name
)
361 go_error_at(location
, "expected package %<%s%>",
362 Gogo::message_name(this->package_
->package_name()).c_str());
366 // Now that we know the name of the package we are compiling, set
367 // the package path to use for reflect.Type.PkgPath and global
369 if (this->pkgpath_set_
)
370 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
373 if (!this->prefix_from_option_
&& package_name
== "main")
375 this->pkgpath_
= package_name
;
376 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
380 if (!this->prefix_from_option_
)
381 this->prefix_
= "go";
382 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
383 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
384 + Gogo::pkgpath_for_symbol(package_name
));
386 this->pkgpath_set_
= true;
389 this->package_
= this->register_package(this->pkgpath_
,
390 this->pkgpath_symbol_
, location
);
391 this->package_
->set_package_name(package_name
, location
);
393 if (this->is_main_package())
395 // Declare "main" as a function which takes no parameters and
397 Location uloc
= Linemap::unknown_location();
398 this->declare_function(Gogo::pack_hidden_name("main", false),
399 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
404 // Return whether this is the "main" package. This is not true if
405 // -fgo-pkgpath or -fgo-prefix was used.
408 Gogo::is_main_package() const
410 return (this->package_name() == "main"
411 && !this->pkgpath_from_option_
412 && !this->prefix_from_option_
);
418 Gogo::import_package(const std::string
& filename
,
419 const std::string
& local_name
,
420 bool is_local_name_exported
,
424 if (filename
.empty())
426 go_error_at(location
, "import path is empty");
430 const char *pf
= filename
.data();
431 const char *pend
= pf
+ filename
.length();
435 int adv
= Lex::fetch_char(pf
, &c
);
438 go_error_at(location
, "import path contains invalid UTF-8 sequence");
443 go_error_at(location
, "import path contains NUL");
446 if (c
< 0x20 || c
== 0x7f)
448 go_error_at(location
, "import path contains control character");
453 go_error_at(location
, "import path contains backslash; use slash");
456 if (Lex::is_unicode_space(c
))
458 go_error_at(location
, "import path contains space character");
461 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
463 go_error_at(location
,
464 "import path contains invalid character '%c'", c
);
470 if (IS_ABSOLUTE_PATH(filename
.c_str()))
472 go_error_at(location
, "import path cannot be absolute path");
476 if (local_name
== "init")
477 go_error_at(location
, "cannot import package as init");
479 if (filename
== "unsafe")
481 this->import_unsafe(local_name
, is_local_name_exported
, location
);
482 this->current_file_imported_unsafe_
= true;
486 if (filename
== "embed")
487 this->current_file_imported_embed_
= true;
489 Imports::const_iterator p
= this->imports_
.find(filename
);
490 if (p
!= this->imports_
.end())
492 Package
* package
= p
->second
;
493 package
->set_location(location
);
494 std::string ln
= local_name
;
495 bool is_ln_exported
= is_local_name_exported
;
498 ln
= package
->package_name();
499 go_assert(!ln
.empty());
500 is_ln_exported
= Lex::is_exported_name(ln
);
506 Bindings
* bindings
= package
->bindings();
507 for (Bindings::const_declarations_iterator pd
=
508 bindings
->begin_declarations();
509 pd
!= bindings
->end_declarations();
511 this->add_dot_import_object(pd
->second
);
512 std::string dot_alias
= "." + package
->package_name();
513 package
->add_alias(dot_alias
, location
);
517 package
->add_alias(ln
, location
);
518 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
519 this->package_
->bindings()->add_package(ln
, package
);
524 // If we are using an importcfg file we have to check two mappings.
525 // IMPORT_MAP_ is a mapping from package path to real package path,
526 // for vendoring. PACKAGE_FILE_ is a mapping from package path to
527 // file name, to find the file in the build cache.
528 std::string path
= filename
;
529 Unordered_map(std::string
, std::string
)::const_iterator pi
;
530 pi
= this->import_map_
.find(filename
);
531 if (pi
!= this->import_map_
.end())
533 pi
= this->package_file_
.find(path
);
534 if (pi
!= this->package_file_
.end())
537 Import::Stream
* stream
= Import::open_package(path
, location
,
538 this->relative_import_path_
);
542 go_error_at(location
, "import file %qs not found", filename
.c_str());
546 Import
* imp
= new Import(stream
, location
);
547 imp
->register_builtin_types(this);
548 Package
* package
= imp
->import(this, local_name
, is_local_name_exported
);
551 if (package
->pkgpath() == this->pkgpath())
552 go_error_at(location
,
553 ("imported package uses same package path as package "
554 "being compiled (see %<-fgo-pkgpath%> option)"));
556 this->imports_
.insert(std::make_pair(filename
, package
));
562 // FIXME: we never delete imp; we may need it for inlinable functions.
566 Gogo::lookup_init(const std::string
& init_name
)
568 Import_init
tmp("", init_name
, -1);
569 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
570 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
573 // Add an import control function for an imported package to the list.
576 Gogo::add_import_init_fn(const std::string
& package_name
,
577 const std::string
& init_name
, int prio
)
579 for (Import_init_set::iterator p
=
580 this->imported_init_fns_
.begin();
581 p
!= this->imported_init_fns_
.end();
584 Import_init
*ii
= (*p
);
585 if (ii
->init_name() == init_name
)
587 // If a test of package P1, built as part of package P1,
588 // imports package P2, and P2 imports P1 (perhaps
589 // indirectly), then we will see the same import name with
590 // different import priorities. That is OK, so don't give
591 // an error about it.
592 if (ii
->package_name() != package_name
)
594 go_error_at(Linemap::unknown_location(),
595 "duplicate package initialization name %qs",
596 Gogo::message_name(init_name
).c_str());
597 go_inform(Linemap::unknown_location(), "used by package %qs",
598 Gogo::message_name(ii
->package_name()).c_str());
599 go_inform(Linemap::unknown_location(), " and by package %qs",
600 Gogo::message_name(package_name
).c_str());
602 ii
->set_priority(prio
);
607 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
608 this->imported_init_fns_
.insert(nii
);
611 // Return whether we are at the global binding level.
614 Gogo::in_global_scope() const
616 return this->functions_
.empty();
619 // Return the current binding contour.
622 Gogo::current_bindings()
624 if (!this->functions_
.empty())
625 return this->functions_
.back().blocks
.back()->bindings();
626 else if (this->package_
!= NULL
)
627 return this->package_
->bindings();
629 return this->globals_
;
633 Gogo::current_bindings() const
635 if (!this->functions_
.empty())
636 return this->functions_
.back().blocks
.back()->bindings();
637 else if (this->package_
!= NULL
)
638 return this->package_
->bindings();
640 return this->globals_
;
644 Gogo::update_init_priority(Import_init
* ii
,
645 std::set
<const Import_init
*>* visited
)
650 for (std::set
<std::string
>::const_iterator pci
=
651 ii
->precursors().begin();
652 pci
!= ii
->precursors().end();
655 Import_init
* succ
= this->lookup_init(*pci
);
656 if (visited
->find(succ
) == visited
->end())
657 update_init_priority(succ
, visited
);
658 succ_prior
= std::max(succ_prior
, succ
->priority());
660 if (ii
->priority() <= succ_prior
)
661 ii
->set_priority(succ_prior
+ 1);
665 Gogo::recompute_init_priorities()
667 std::set
<Import_init
*> nonroots
;
669 for (Import_init_set::const_iterator p
=
670 this->imported_init_fns_
.begin();
671 p
!= this->imported_init_fns_
.end();
674 const Import_init
*ii
= *p
;
675 for (std::set
<std::string
>::const_iterator pci
=
676 ii
->precursors().begin();
677 pci
!= ii
->precursors().end();
680 Import_init
* ii_init
= this->lookup_init(*pci
);
681 nonroots
.insert(ii_init
);
685 // Recursively update priorities starting at roots.
686 std::set
<const Import_init
*> visited
;
687 for (Import_init_set::iterator p
=
688 this->imported_init_fns_
.begin();
689 p
!= this->imported_init_fns_
.end();
692 Import_init
* ii
= *p
;
693 if (nonroots
.find(ii
) != nonroots
.end())
695 update_init_priority(ii
, &visited
);
699 // Add statements to INIT_STMTS which run the initialization
700 // functions for imported packages. This is only used for the "main"
704 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
, Bfunction
*bfunction
)
706 go_assert(this->is_main_package());
708 if (this->imported_init_fns_
.empty())
711 Location unknown_loc
= Linemap::unknown_location();
712 Function_type
* func_type
=
713 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
714 Btype
* fntype
= func_type
->get_backend_fntype(this);
716 // Recompute init priorities based on a walk of the init graph.
717 recompute_init_priorities();
719 // We must call them in increasing priority order.
720 std::vector
<const Import_init
*> v
;
721 for (Import_init_set::const_iterator p
=
722 this->imported_init_fns_
.begin();
723 p
!= this->imported_init_fns_
.end();
726 // Don't include dummy inits. They are not real functions.
727 if ((*p
)->is_dummy())
729 if ((*p
)->priority() < 0)
730 go_error_at(Linemap::unknown_location(),
731 "internal error: failed to set init priority for %s",
732 (*p
)->package_name().c_str());
735 std::sort(v
.begin(), v
.end(), priority_compare
);
737 // We build calls to the init functions, which take no arguments.
738 std::vector
<Bexpression
*> empty_args
;
739 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
743 const Import_init
* ii
= *p
;
744 std::string user_name
= ii
->package_name() + ".init";
745 const std::string
& init_name(ii
->init_name());
746 const unsigned int flags
=
747 (Backend::function_is_visible
748 | Backend::function_is_declaration
749 | Backend::function_is_inlinable
);
750 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
752 Bexpression
* pfunc_code
=
753 this->backend()->function_code_expression(pfunc
, unknown_loc
);
754 Bexpression
* pfunc_call
=
755 this->backend()->call_expression(bfunction
, pfunc_code
, empty_args
,
757 init_stmts
.push_back(this->backend()->expression_statement(bfunction
,
762 // Register global variables with the garbage collector. We need to
763 // register all variables which can hold a pointer value. They become
764 // roots during the mark phase. We build a struct that is easy to
765 // hook into a list of roots.
767 // type gcRoot struct {
768 // decl unsafe.Pointer // Pointer to variable.
769 // size uintptr // Total size of variable.
770 // ptrdata uintptr // Length of variable's gcdata.
771 // gcdata *byte // Pointer mask.
774 // type gcRootList struct {
780 // The last entry in the roots array has a NULL decl field.
783 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
784 std::vector
<Bstatement
*>& init_stmts
,
787 if (var_gc
.empty() && this->gc_roots_
.empty())
790 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
791 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
792 Type
* byte_type
= Type::lookup_integer_type("byte");
793 Type
* pointer_byte_type
= Type::make_pointer_type(byte_type
);
794 Struct_type
* root_type
=
795 Type::make_builtin_struct_type(4,
797 "size", uintptr_type
,
798 "ptrdata", uintptr_type
,
799 "gcdata", pointer_byte_type
);
801 Location builtin_loc
= Linemap::predeclared_location();
802 unsigned long roots_len
= var_gc
.size() + this->gc_roots_
.size();
803 Expression
* length
= Expression::make_integer_ul(roots_len
, NULL
,
805 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
806 root_array_type
->set_is_array_incomparable();
808 Type
* int_type
= Type::lookup_integer_type("int");
809 Struct_type
* root_list_type
=
810 Type::make_builtin_struct_type(3,
813 "roots", root_array_type
);
815 // Build an initializer for the roots array.
817 Expression_list
* roots_init
= new Expression_list();
819 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
823 Expression_list
* init
= new Expression_list();
825 Location no_loc
= (*p
)->location();
826 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
827 Expression
* decl_addr
=
828 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
829 decl_addr
->unary_expression()->set_does_not_escape();
830 decl_addr
= Expression::make_cast(pvt
, decl_addr
, no_loc
);
831 init
->push_back(decl_addr
);
834 Expression::make_type_info(decl
->type(),
835 Expression::TYPE_INFO_SIZE
);
836 init
->push_back(size
);
838 Expression
* ptrdata
=
839 Expression::make_type_info(decl
->type(),
840 Expression::TYPE_INFO_BACKEND_PTRDATA
);
841 init
->push_back(ptrdata
);
843 Expression
* gcdata
= Expression::make_ptrmask_symbol(decl
->type());
844 init
->push_back(gcdata
);
846 Expression
* root_ctor
=
847 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
848 roots_init
->push_back(root_ctor
);
851 for (std::vector
<Expression
*>::const_iterator p
= this->gc_roots_
.begin();
852 p
!= this->gc_roots_
.end();
855 Expression_list
*init
= new Expression_list();
857 Expression
* expr
= *p
;
858 Location eloc
= expr
->location();
859 init
->push_back(Expression::make_cast(pvt
, expr
, eloc
));
861 Type
* type
= expr
->type()->points_to();
862 go_assert(type
!= NULL
);
865 Expression::make_type_info(type
,
866 Expression::TYPE_INFO_SIZE
);
867 init
->push_back(size
);
869 Expression
* ptrdata
=
870 Expression::make_type_info(type
,
871 Expression::TYPE_INFO_BACKEND_PTRDATA
);
872 init
->push_back(ptrdata
);
874 Expression
* gcdata
= Expression::make_ptrmask_symbol(type
);
875 init
->push_back(gcdata
);
877 Expression
* root_ctor
=
878 Expression::make_struct_composite_literal(root_type
, init
, eloc
);
879 roots_init
->push_back(root_ctor
);
882 // Build a constructor for the struct.
884 Expression_list
* root_list_init
= new Expression_list();
885 root_list_init
->push_back(Expression::make_nil(builtin_loc
));
886 root_list_init
->push_back(Expression::make_integer_ul(roots_len
, int_type
,
889 Expression
* roots_ctor
=
890 Expression::make_array_composite_literal(root_array_type
, roots_init
,
892 root_list_init
->push_back(roots_ctor
);
894 Expression
* root_list_ctor
=
895 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
898 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
900 root_addr
->unary_expression()->set_is_gc_root();
901 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
902 builtin_loc
, 1, root_addr
);
904 Translate_context
context(this, NULL
, NULL
, NULL
);
905 Bexpression
* bcall
= register_roots
->get_backend(&context
);
906 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
, bcall
));
909 // Build the list of type descriptors defined in this package. This is to help
910 // the reflect package to find compiler-generated types.
912 // type typeDescriptorList struct {
914 // types [...]unsafe.Pointer
918 type_descriptor_list_type(unsigned long len
)
920 Location builtin_loc
= Linemap::predeclared_location();
921 Type
* int_type
= Type::lookup_integer_type("int");
922 Type
* ptr_type
= Type::make_pointer_type(Type::make_void_type());
923 // Avoid creating zero-length type.
924 unsigned long nelems
= (len
!= 0 ? len
: 1);
925 Expression
* len_expr
= Expression::make_integer_ul(nelems
, NULL
,
927 Array_type
* array_type
= Type::make_array_type(ptr_type
, len_expr
);
928 array_type
->set_is_array_incomparable();
929 Struct_type
* list_type
=
930 Type::make_builtin_struct_type(2, "count", int_type
,
931 "types", array_type
);
936 Gogo::build_type_descriptor_list()
938 // Create the list type
939 Location builtin_loc
= Linemap::predeclared_location();
940 unsigned long len
= this->type_descriptors_
.size();
941 Struct_type
* list_type
= type_descriptor_list_type(len
);
942 Btype
* bt
= list_type
->get_backend(this);
943 Btype
* bat
= list_type
->field(1)->type()->get_backend(this);
945 // Create the variable
946 std::string name
= this->type_descriptor_list_symbol(this->pkgpath_symbol());
947 unsigned int flags
= Backend::variable_is_constant
;
948 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bt
, flags
, 0);
950 // Build the initializer
951 std::vector
<unsigned long> indexes
;
952 std::vector
<Bexpression
*> vals
;
953 std::vector
<Type
*>::iterator p
= this->type_descriptors_
.begin();
954 for (unsigned long i
= 0; i
< len
; ++i
, ++p
)
956 Bexpression
* bexpr
= (*p
)->type_descriptor_pointer(this,
958 indexes
.push_back(i
);
959 vals
.push_back(bexpr
);
961 Bexpression
* barray
=
962 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
965 Translate_context
context(this, NULL
, NULL
, NULL
);
966 std::vector
<Bexpression
*> fields
;
967 Expression
* len_expr
= Expression::make_integer_ul(len
, NULL
,
969 fields
.push_back(len_expr
->get_backend(&context
));
970 fields
.push_back(barray
);
972 this->backend()->constructor_expression(bt
, fields
, builtin_loc
);
974 this->backend()->implicit_variable_set_init(bv
, name
, bt
, flags
, binit
);
977 // Register the type descriptors with the runtime. This is to help
978 // the reflect package to find compiler-generated types.
981 Gogo::register_type_descriptors(std::vector
<Bstatement
*>& init_stmts
,
984 // Create the list type
985 Location builtin_loc
= Linemap::predeclared_location();
986 Struct_type
* list_type
= type_descriptor_list_type(1);
987 Btype
* bt
= list_type
->get_backend(this);
989 // Collect type lists from transitive imports.
990 std::vector
<std::string
> list_names
;
991 for (Import_init_set::iterator it
= this->imported_init_fns_
.begin();
992 it
!= this->imported_init_fns_
.end();
995 std::string pkgpath_symbol
=
996 this->pkgpath_symbol_from_init_fn_name((*it
)->init_name());
997 list_names
.push_back(this->type_descriptor_list_symbol(pkgpath_symbol
));
999 // Add the main package itself.
1000 list_names
.push_back(this->type_descriptor_list_symbol("main"));
1002 // Build a list of lists.
1003 std::vector
<unsigned long> indexes
;
1004 std::vector
<Bexpression
*> vals
;
1005 unsigned long i
= 0;
1006 for (std::vector
<std::string
>::iterator p
= list_names
.begin();
1007 p
!= list_names
.end();
1011 this->backend()->implicit_variable_reference(*p
, *p
, bt
);
1012 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
1013 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
1015 indexes
.push_back(i
);
1016 vals
.push_back(bexpr
);
1019 Expression
* len_expr
= Expression::make_integer_ul(i
, NULL
, builtin_loc
);
1020 Type
* list_ptr_type
= Type::make_pointer_type(list_type
);
1021 Type
* list_array_type
= Type::make_array_type(list_ptr_type
, len_expr
);
1022 Btype
* bat
= list_array_type
->get_backend(this);
1023 Bexpression
* barray
=
1024 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
1027 // Create a variable holding the list.
1028 std::string name
= this->typelists_symbol();
1029 unsigned int flags
= (Backend::variable_is_hidden
1030 | Backend::variable_is_constant
);
1031 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bat
, flags
,
1033 this->backend()->implicit_variable_set_init(bv
, name
, bat
, flags
, barray
);
1035 // Build the call in main package's init function.
1036 Translate_context
context(this, NULL
, NULL
, NULL
);
1037 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
1038 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
1039 Type
* array_ptr_type
= Type::make_pointer_type(list_array_type
);
1040 Expression
* expr
= Expression::make_backend(bexpr
, array_ptr_type
,
1042 expr
= Runtime::make_call(Runtime::REGISTER_TYPE_DESCRIPTORS
,
1043 builtin_loc
, 2, len_expr
->copy(), expr
);
1044 Bexpression
* bcall
= expr
->get_backend(&context
);
1045 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
,
1049 // Build the decl for the initialization function.
1052 Gogo::initialization_function_decl()
1054 std::string name
= this->get_init_fn_name();
1055 Location loc
= this->package_
->location();
1057 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
1058 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
1059 return Named_object::make_function(name
, NULL
, initfn
);
1062 // Create the magic initialization function. CODE_STMT is the
1063 // code that it needs to run.
1066 Gogo::create_initialization_function(Named_object
* initfn
,
1067 Bstatement
* code_stmt
)
1069 // Make sure that we thought we needed an initialization function,
1070 // as otherwise we will not have reported it in the export data.
1071 go_assert(this->is_main_package() || this->need_init_fn_
);
1074 initfn
= this->initialization_function_decl();
1076 // Bind the initialization function code to a block.
1077 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
1078 Location pkg_loc
= this->package_
->location();
1079 std::vector
<Bvariable
*> vars
;
1080 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
1082 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
1084 go_assert(saw_errors());
1090 // Given an expression, collect all the global variables defined in
1091 // this package that it references.
1093 class Find_vars
: public Traverse
1096 // The list of variables we accumulate.
1097 typedef Unordered_set(Named_object
*) Vars
;
1099 // A hash table we use to avoid looping. The index is a
1100 // Named_object* or a Temporary_statement*. We only look through
1101 // objects defined in this package.
1102 typedef Unordered_set(const void*) Seen_objects
;
1106 : Traverse(traverse_expressions
| traverse_statements
),
1107 vars_(), seen_objects_(), lhs_is_ref_(false)
1110 // An iterator through the variables found, after the traversal.
1111 typedef Vars::const_iterator const_iterator
;
1115 { return this->vars_
.begin(); }
1119 { return this->vars_
.end(); }
1122 expression(Expression
**);
1125 statement(Block
*, size_t* index
, Statement
*);
1128 // Accumulated variables.
1130 // Objects we have already seen.
1131 Seen_objects seen_objects_
;
1132 // Whether an assignment to a variable counts as a reference.
1136 // Collect global variables referenced by EXPR. Look through function
1137 // calls and variable initializations.
1140 Find_vars::expression(Expression
** pexpr
)
1142 Expression
* e
= *pexpr
;
1144 Var_expression
* ve
= e
->var_expression();
1147 Named_object
* v
= ve
->named_object();
1148 if (!v
->is_variable() || v
->package() != NULL
)
1150 // This is a result parameter or a variable defined in a
1151 // different package. Either way we don't care about it.
1152 return TRAVERSE_CONTINUE
;
1155 std::pair
<Seen_objects::iterator
, bool> ins
=
1156 this->seen_objects_
.insert(v
);
1159 // We've seen this variable before.
1160 return TRAVERSE_CONTINUE
;
1163 if (v
->var_value()->is_global())
1164 this->vars_
.insert(v
);
1166 Expression
* init
= v
->var_value()->init();
1169 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1170 return TRAVERSE_EXIT
;
1174 // We traverse the code of any function or bound method we see. Note that
1175 // this means that we will traverse the code of a function or bound method
1176 // whose address is taken even if it is not called.
1177 Func_expression
* fe
= e
->func_expression();
1178 Bound_method_expression
* bme
= e
->bound_method_expression();
1179 if (fe
!= NULL
|| bme
!= NULL
)
1181 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1182 if (f
->is_function() && f
->package() == NULL
)
1184 std::pair
<Seen_objects::iterator
, bool> ins
=
1185 this->seen_objects_
.insert(f
);
1188 // This is the first time we have seen this name.
1189 bool hold
= this->lhs_is_ref_
;
1190 this->lhs_is_ref_
= true;
1191 int r
= f
->func_value()->block()->traverse(this);
1192 this->lhs_is_ref_
= hold
;
1193 if (r
== TRAVERSE_EXIT
)
1194 return TRAVERSE_EXIT
;
1199 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1202 Temporary_statement
* ts
= tre
->statement();
1203 Expression
* init
= ts
->init();
1206 std::pair
<Seen_objects::iterator
, bool> ins
=
1207 this->seen_objects_
.insert(ts
);
1210 // This is the first time we have seen this temporary
1212 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1213 return TRAVERSE_EXIT
;
1218 return TRAVERSE_CONTINUE
;
1221 // Check a statement while searching for variables. This is where we
1222 // skip variables on the left hand side of assigments if appropriate.
1225 Find_vars::statement(Block
*, size_t*, Statement
* s
)
1227 if (this->lhs_is_ref_
)
1228 return TRAVERSE_CONTINUE
;
1229 Assignment_statement
* as
= s
->assignment_statement();
1231 return TRAVERSE_CONTINUE
;
1233 // Only traverse subexpressions of the LHS.
1234 if (as
->lhs()->traverse_subexpressions(this) == TRAVERSE_EXIT
)
1235 return TRAVERSE_EXIT
;
1237 Expression
* rhs
= as
->rhs();
1238 if (Expression::traverse(&rhs
, this) == TRAVERSE_EXIT
)
1239 return TRAVERSE_EXIT
;
1241 return TRAVERSE_SKIP_COMPONENTS
;
1244 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1247 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1250 Find_vars find_vars
;
1252 Expression::traverse(&expr
, &find_vars
);
1253 if (preinit
!= NULL
)
1254 preinit
->traverse(&find_vars
);
1257 Expression
* init
= dep
->var_value()->init();
1259 Expression::traverse(&init
, &find_vars
);
1260 if (dep
->var_value()->has_pre_init())
1261 dep
->var_value()->preinit()->traverse(&find_vars
);
1264 for (Find_vars::const_iterator p
= find_vars
.begin();
1265 p
!= find_vars
.end();
1274 // Sort variable initializations. If the initialization expression
1275 // for variable A refers directly or indirectly to the initialization
1276 // expression for variable B, then we must initialize B before A.
1282 : var_(NULL
), init_(NULL
), dep_count_(0)
1285 Var_init(Named_object
* var
, Bstatement
* init
)
1286 : var_(var
), init_(init
), dep_count_(0)
1289 // Return the variable.
1292 { return this->var_
; }
1294 // Return the initialization expression.
1297 { return this->init_
; }
1299 // Return the number of remaining dependencies.
1302 { return this->dep_count_
; }
1304 // Increment the number of dependencies.
1307 { ++this->dep_count_
; }
1309 // Decrement the number of dependencies.
1312 { --this->dep_count_
; }
1315 // The variable being initialized.
1317 // The backend initialization statement.
1319 // The number of initializations this is dependent on. A variable
1320 // initialization should not be emitted if any of its dependencies
1321 // have not yet been resolved.
1325 // For comparing Var_init keys in a map.
1328 operator<(const Var_init
& v1
, const Var_init
& v2
)
1329 { return v1
.var()->name() < v2
.var()->name(); }
1331 typedef std::list
<Var_init
> Var_inits
;
1333 // Sort the variable initializations. The rule we follow is that we
1334 // emit them in the order they appear in the array, except that if the
1335 // initialization expression for a variable V1 depends upon another
1336 // variable V2 then we initialize V1 after V2.
1339 sort_var_inits(Var_inits
* var_inits
)
1341 if (var_inits
->empty())
1344 std::map
<Named_object
*, Var_init
*> var_to_init
;
1346 // A mapping from a variable initialization to a set of
1347 // variable initializations that depend on it.
1348 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1349 Init_deps init_deps
;
1350 bool init_loop
= false;
1352 // Map from variable to Var_init.
1353 for (Var_inits::iterator pvar
= var_inits
->begin();
1354 pvar
!= var_inits
->end();
1357 Named_object
* var
= pvar
->var();
1358 var_to_init
[var
] = &*pvar
;
1361 // Add dependencies to init_deps, and check for cycles.
1362 for (Var_inits::iterator pvar
= var_inits
->begin();
1363 pvar
!= var_inits
->end();
1366 Named_object
* var
= pvar
->var();
1368 const std::vector
<Named_object
*>* refs
=
1369 pvar
->var()->var_value()->init_refs();
1372 for (std::vector
<Named_object
*>::const_iterator pdep
= refs
->begin();
1373 pdep
!= refs
->end();
1376 Named_object
* dep
= *pdep
;
1379 // This is a reference from a variable to itself.
1380 go_error_at(var
->location(),
1381 ("initialization expression for %qs "
1382 "depends upon itself"),
1383 var
->message_name().c_str());
1387 Var_init
* dep_init
= var_to_init
[dep
];
1388 if (dep_init
== NULL
)
1390 // This is a dependency on some variable that doesn't
1391 // have an initializer, so for purposes of
1392 // initialization ordering this is irrelevant.
1396 init_deps
[*dep_init
].insert(&(*pvar
));
1397 pvar
->add_dependency();
1399 // Check for cycles.
1400 const std::vector
<Named_object
*>* deprefs
=
1401 dep_init
->var()->var_value()->init_refs();
1402 if (deprefs
== NULL
)
1404 for (std::vector
<Named_object
*>::const_iterator pdepdep
=
1406 pdepdep
!= deprefs
->end();
1409 if (*pdepdep
== var
)
1411 go_error_at(var
->location(),
1412 ("initialization expressions for %qs and "
1413 "%qs depend upon each other"),
1414 var
->message_name().c_str(),
1415 dep
->message_name().c_str());
1416 go_inform(dep
->location(), "%qs defined here",
1417 dep
->message_name().c_str());
1425 var_to_init
.clear();
1427 // If there are no dependencies then the declaration order is sorted.
1428 if (!init_deps
.empty() && !init_loop
)
1430 // Otherwise, sort variable initializations by emitting all variables with
1431 // no dependencies in declaration order. VAR_INITS is already in
1432 // declaration order.
1434 while (!var_inits
->empty())
1436 Var_inits::iterator v1
;;
1437 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1439 if (v1
->dep_count() == 0)
1442 go_assert(v1
!= var_inits
->end());
1444 // V1 either has no dependencies or its dependencies have already
1445 // been emitted, add it to READY next. When V1 is emitted, remove
1446 // a dependency from each V that depends on V1.
1447 ready
.splice(ready
.end(), *var_inits
, v1
);
1449 Init_deps::iterator p1
= init_deps
.find(*v1
);
1450 if (p1
!= init_deps
.end())
1452 std::set
<Var_init
*> resolved
= p1
->second
;
1453 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1454 pv
!= resolved
.end();
1456 (*pv
)->remove_dependency();
1457 init_deps
.erase(p1
);
1460 var_inits
->swap(ready
);
1461 go_assert(init_deps
.empty());
1465 // Give an error if the initialization expression for VAR depends on
1466 // itself. We only check if INIT is not NULL and there is no
1467 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1468 // which we will interpret as a loop.
1471 Gogo::check_self_dep(Named_object
* var
)
1473 Expression
* init
= var
->var_value()->init();
1474 Block
* preinit
= var
->var_value()->preinit();
1475 Named_object
* dep
= this->var_depends_on(var
->var_value());
1478 && expression_requires(init
, preinit
, NULL
, var
))
1479 go_error_at(var
->location(),
1480 "initialization expression for %qs depends upon itself",
1481 var
->message_name().c_str());
1484 // Write out the global definitions.
1487 Gogo::write_globals()
1489 this->build_interface_method_tables();
1491 Bindings
* bindings
= this->current_bindings();
1493 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1494 p
!= bindings
->end_declarations();
1497 // If any function declarations needed a descriptor, make sure
1499 Named_object
* no
= p
->second
;
1500 if (no
->is_function_declaration())
1501 no
->func_declaration_value()->build_backend_descriptor(this);
1504 // Lists of globally declared types, variables, constants, and functions
1505 // that must be defined.
1506 std::vector
<Btype
*> type_decls
;
1507 std::vector
<Bvariable
*> var_decls
;
1508 std::vector
<Bexpression
*> const_decls
;
1509 std::vector
<Bfunction
*> func_decls
;
1511 // The init function declaration and associated Bfunction, if necessary.
1512 Named_object
* init_fndecl
= NULL
;
1513 Bfunction
* init_bfn
= NULL
;
1515 std::vector
<Bstatement
*> init_stmts
;
1516 std::vector
<Bstatement
*> var_init_stmts
;
1518 if (this->is_main_package())
1520 init_fndecl
= this->initialization_function_decl();
1521 init_bfn
= init_fndecl
->func_value()->get_or_make_decl(this, init_fndecl
);
1524 // A list of variable initializations.
1525 Var_inits var_inits
;
1527 // A list of variables which need to be registered with the garbage
1529 size_t count_definitions
= bindings
->size_definitions();
1530 std::vector
<Named_object
*> var_gc
;
1531 var_gc
.reserve(count_definitions
);
1533 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1534 p
!= bindings
->end_definitions();
1537 Named_object
* no
= *p
;
1538 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1540 // There is nothing to do for a package.
1541 if (no
->is_package())
1544 // There is nothing to do for an object which was imported from
1545 // a different package into the global scope.
1546 if (no
->package() != NULL
)
1549 // Skip blank named functions and constants.
1550 if ((no
->is_function() && no
->func_value()->is_sink())
1551 || (no
->is_const() && no
->const_value()->is_sink()))
1554 // Skip global sink variables with static initializers. With
1555 // non-static initializers we have to evaluate for side effects,
1556 // and we wind up initializing a dummy variable. That is not
1557 // ideal but it works and it's a rare case.
1558 if (no
->is_variable()
1559 && no
->var_value()->is_global_sink()
1560 && !no
->var_value()->has_pre_init()
1561 && (no
->var_value()->init() == NULL
1562 || no
->var_value()->init()->is_static_initializer()))
1565 // There is nothing useful we can output for constants which
1566 // have ideal or non-integral type.
1569 Type
* type
= no
->const_value()->type();
1571 type
= no
->const_value()->expr()->type();
1572 if (type
->is_abstract() || !type
->is_numeric_type())
1576 if (!no
->is_variable())
1577 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1580 Variable
* var
= no
->var_value();
1581 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1582 var_decls
.push_back(bvar
);
1584 // Check for a sink variable, which may be used to run an
1585 // initializer purely for its side effects.
1586 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1588 Bstatement
* var_init_stmt
= NULL
;
1589 if (!var
->has_pre_init())
1591 // If the backend representation of the variable initializer is
1592 // constant, we can just set the initial value using
1593 // global_var_set_init instead of during the init() function.
1594 // The initializer is constant if it is the zero-value of the
1595 // variable's type or if the initial value is an immutable value
1596 // that is not copied to the heap.
1597 bool is_static_initializer
= false;
1598 if (var
->init() == NULL
)
1599 is_static_initializer
= true;
1602 Type
* var_type
= var
->type();
1603 Expression
* init
= var
->init();
1604 Expression
* init_cast
=
1605 Expression::make_cast(var_type
, init
, var
->location());
1606 is_static_initializer
= init_cast
->is_static_initializer();
1609 // Non-constant variable initializations might need to create
1610 // temporary variables, which will need the initialization
1611 // function as context.
1612 Named_object
* var_init_fn
;
1613 if (is_static_initializer
)
1617 if (init_fndecl
== NULL
)
1619 init_fndecl
= this->initialization_function_decl();
1620 Function
* func
= init_fndecl
->func_value();
1621 init_bfn
= func
->get_or_make_decl(this, init_fndecl
);
1623 var_init_fn
= init_fndecl
;
1625 Bexpression
* var_binit
= var
->get_init(this, var_init_fn
);
1627 if (var_binit
== NULL
)
1629 else if (is_static_initializer
)
1631 if (expression_requires(var
->init(), NULL
,
1632 this->var_depends_on(var
), no
))
1633 go_error_at(no
->location(),
1634 "initialization expression for %qs depends "
1636 no
->message_name().c_str());
1637 this->backend()->global_variable_set_init(bvar
, var_binit
);
1641 this->backend()->expression_statement(init_bfn
, var_binit
);
1644 Location loc
= var
->location();
1645 Bexpression
* var_expr
=
1646 this->backend()->var_expression(bvar
, loc
);
1648 this->backend()->assignment_statement(init_bfn
, var_expr
,
1654 // We are going to create temporary variables which
1655 // means that we need an fndecl.
1656 if (init_fndecl
== NULL
)
1657 init_fndecl
= this->initialization_function_decl();
1659 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1660 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1663 if (var_init_stmt
!= NULL
)
1665 if (var
->init() == NULL
&& !var
->has_pre_init())
1666 var_init_stmts
.push_back(var_init_stmt
);
1668 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1670 else if (this->var_depends_on(var
) != NULL
)
1672 // This variable is initialized from something that is
1673 // not in its init or preinit. This variable needs to
1674 // participate in dependency analysis sorting, in case
1675 // some other variable depends on this one.
1676 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1677 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1678 Bstatement
* zero_stmt
=
1679 this->backend()->expression_statement(init_bfn
, zero
);
1680 var_inits
.push_back(Var_init(no
, zero_stmt
));
1683 // Collect a list of all global variables with pointers,
1684 // to register them for the garbage collector.
1685 if (!is_sink
&& var
->type()->has_pointer())
1687 // Avoid putting runtime.gcRoots itself on the list.
1688 if (this->compiling_runtime()
1689 && this->package_name() == "runtime"
1690 && (Gogo::unpack_hidden_name(no
->name()) == "gcRoots"
1691 || Gogo::unpack_hidden_name(no
->name()) == "gcRootsIndex"))
1694 var_gc
.push_back(no
);
1699 // Output inline functions, which are in different packages.
1700 for (std::vector
<Named_object
*>::const_iterator p
=
1701 this->imported_inline_functions_
.begin();
1702 p
!= this->imported_inline_functions_
.end();
1704 (*p
)->get_backend(this, const_decls
, type_decls
, func_decls
);
1706 // Build the list of type descriptors.
1707 this->build_type_descriptor_list();
1709 if (this->is_main_package())
1711 // Register the type descriptor lists, so that at run time
1712 // the reflect package can find compiler-created types, and
1713 // deduplicate if the same type is created with reflection.
1714 // This needs to be done before calling any package's init
1715 // function, as it may create type through reflection.
1716 this->register_type_descriptors(init_stmts
, init_bfn
);
1718 // Initialize imported packages.
1719 this->init_imports(init_stmts
, init_bfn
);
1722 // Register global variables with the garbage collector.
1723 this->register_gc_vars(var_gc
, init_stmts
, init_bfn
);
1725 // Simple variable initializations, after all variables are
1727 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1729 // Complete variable initializations, first sorting them into a
1731 if (!var_inits
.empty())
1733 sort_var_inits(&var_inits
);
1734 for (Var_inits::const_iterator p
= var_inits
.begin();
1735 p
!= var_inits
.end();
1737 init_stmts
.push_back(p
->init());
1740 // After all the variables are initialized, call the init
1741 // functions if there are any. Init functions take no arguments, so
1742 // we pass in EMPTY_ARGS to call them.
1743 std::vector
<Bexpression
*> empty_args
;
1744 for (std::vector
<Named_object
*>::const_iterator p
=
1745 this->init_functions_
.begin();
1746 p
!= this->init_functions_
.end();
1749 Location func_loc
= (*p
)->location();
1750 Function
* func
= (*p
)->func_value();
1751 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1752 Bexpression
* func_code
=
1753 this->backend()->function_code_expression(initfn
, func_loc
);
1754 Bexpression
* call
= this->backend()->call_expression(init_bfn
, func_code
,
1757 Bstatement
* ist
= this->backend()->expression_statement(init_bfn
, call
);
1758 init_stmts
.push_back(ist
);
1761 // Set up a magic function to do all the initialization actions.
1762 // This will be called if this package is imported.
1763 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1764 if (this->need_init_fn_
|| this->is_main_package())
1767 this->create_initialization_function(init_fndecl
, init_fncode
);
1768 if (init_fndecl
!= NULL
)
1769 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1772 // We should not have seen any new bindings created during the conversion.
1773 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1775 // Define all globally declared values.
1777 this->backend()->write_global_definitions(type_decls
, const_decls
,
1778 func_decls
, var_decls
);
1781 // Return the current block.
1784 Gogo::current_block()
1786 if (this->functions_
.empty())
1789 return this->functions_
.back().blocks
.back();
1792 // Look up a name in the current binding contour. If PFUNCTION is not
1793 // NULL, set it to the function in which the name is defined, or NULL
1794 // if the name is defined in global scope.
1797 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1799 if (pfunction
!= NULL
)
1802 if (Gogo::is_sink_name(name
))
1803 return Named_object::make_sink();
1805 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1806 p
!= this->functions_
.rend();
1809 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1812 if (pfunction
!= NULL
)
1813 *pfunction
= p
->function
;
1818 if (this->package_
!= NULL
)
1820 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1823 if (ret
->package() != NULL
)
1825 std::string dot_alias
= "." + ret
->package()->package_name();
1826 ret
->package()->note_usage(dot_alias
);
1832 // We do not look in the global namespace. If we did, the global
1833 // namespace would effectively hide names which were defined in
1834 // package scope which we have not yet seen. Instead,
1835 // define_global_names is called after parsing is over to connect
1836 // undefined names at package scope with names defined at global
1842 // Look up a name in the current block, without searching enclosing
1846 Gogo::lookup_in_block(const std::string
& name
) const
1848 go_assert(!this->functions_
.empty());
1849 go_assert(!this->functions_
.back().blocks
.empty());
1850 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1853 // Look up a name in the global namespace.
1856 Gogo::lookup_global(const char* name
) const
1858 return this->globals_
->lookup(name
);
1861 // Add an imported package.
1864 Gogo::add_imported_package(const std::string
& real_name
,
1865 const std::string
& alias_arg
,
1866 bool is_alias_exported
,
1867 const std::string
& pkgpath
,
1868 const std::string
& pkgpath_symbol
,
1870 bool* padd_to_globals
)
1872 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1873 ret
->set_package_name(real_name
, location
);
1875 *padd_to_globals
= false;
1877 if (alias_arg
== "_")
1879 else if (alias_arg
== ".")
1881 *padd_to_globals
= true;
1882 std::string dot_alias
= "." + real_name
;
1883 ret
->add_alias(dot_alias
, location
);
1887 std::string alias
= alias_arg
;
1891 is_alias_exported
= Lex::is_exported_name(alias
);
1893 ret
->add_alias(alias
, location
);
1894 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1895 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1896 if (!no
->is_package())
1903 // Register a package. This package may or may not be imported. This
1904 // returns the Package structure for the package, creating if it
1905 // necessary. LOCATION is the location of the import statement that
1906 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1907 // for names in the package; it may be the empty string, in which case
1908 // we either get it later or make a guess when we need it.
1911 Gogo::register_package(const std::string
& pkgpath
,
1912 const std::string
& pkgpath_symbol
, Location location
)
1914 Package
* package
= NULL
;
1915 std::pair
<Packages::iterator
, bool> ins
=
1916 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1919 // We have seen this package name before.
1920 package
= ins
.first
->second
;
1921 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1922 if (!pkgpath_symbol
.empty())
1923 package
->set_pkgpath_symbol(pkgpath_symbol
);
1924 if (Linemap::is_unknown_location(package
->location()))
1925 package
->set_location(location
);
1929 // First time we have seen this package name.
1930 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1931 go_assert(ins
.first
->second
== NULL
);
1932 ins
.first
->second
= package
;
1938 // Return the pkgpath symbol for a package, given the pkgpath.
1941 Gogo::pkgpath_symbol_for_package(const std::string
& pkgpath
)
1943 Packages::iterator p
= this->packages_
.find(pkgpath
);
1944 go_assert(p
!= this->packages_
.end());
1945 return p
->second
->pkgpath_symbol();
1948 // Start compiling a function.
1951 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1952 bool add_method_to_type
, Location location
)
1954 bool at_top_level
= this->functions_
.empty();
1956 Block
* block
= new Block(NULL
, location
);
1958 Named_object
* enclosing
= (at_top_level
1960 : this->functions_
.back().function
);
1962 Function
* function
= new Function(type
, enclosing
, block
, location
);
1964 if (type
->is_method())
1966 const Typed_identifier
* receiver
= type
->receiver();
1967 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1968 true, true, location
);
1969 std::string rname
= receiver
->name();
1970 unsigned rcounter
= 0;
1972 // We need to give a nameless receiver parameter a synthesized name to
1973 // avoid having it clash with some other nameless param. FIXME.
1974 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
1976 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1979 const Typed_identifier_list
* parameters
= type
->parameters();
1980 bool is_varargs
= type
->is_varargs();
1981 unsigned pcounter
= 0;
1982 if (parameters
!= NULL
)
1984 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1985 p
!= parameters
->end();
1988 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1990 if (is_varargs
&& p
+ 1 == parameters
->end())
1991 param
->set_is_varargs_parameter();
1993 std::string pname
= p
->name();
1995 // We need to give each nameless parameter a non-empty name to avoid
1996 // having it clash with some other nameless param. FIXME.
1997 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
1999 block
->bindings()->add_variable(pname
, NULL
, param
);
2003 function
->create_result_variables(this);
2005 const std::string
* pname
;
2006 std::string nested_name
;
2007 bool is_init
= false;
2008 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
2010 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
2011 || (type
->results() != NULL
&& !type
->results()->empty()))
2012 go_error_at(location
,
2013 "func init must have no arguments and no return values");
2014 // There can be multiple "init" functions, so give them each a
2016 nested_name
= this->init_function_name();
2017 pname
= &nested_name
;
2020 else if (!name
.empty())
2024 // Invent a name for a nested function.
2025 nested_name
= this->nested_function_name(enclosing
);
2026 pname
= &nested_name
;
2030 if (Gogo::is_sink_name(*pname
))
2032 std::string
sname(this->sink_function_name());
2033 ret
= Named_object::make_function(sname
, NULL
, function
);
2034 ret
->func_value()->set_is_sink();
2036 if (!type
->is_method())
2037 ret
= this->package_
->bindings()->add_named_object(ret
);
2038 else if (add_method_to_type
)
2040 // We should report errors even for sink methods.
2041 Type
* rtype
= type
->receiver()->type();
2042 // Avoid points_to and deref to avoid getting an error if
2043 // the type is not yet defined.
2044 if (rtype
->classification() == Type::TYPE_POINTER
)
2045 rtype
= rtype
->points_to();
2046 while (rtype
->named_type() != NULL
2047 && rtype
->named_type()->is_alias())
2048 rtype
= rtype
->named_type()->real_type()->forwarded();
2049 if (rtype
->is_error_type())
2051 else if (rtype
->named_type() != NULL
)
2053 if (rtype
->named_type()->named_object()->package() != NULL
)
2054 go_error_at(type
->receiver()->location(),
2055 "may not define methods on non-local type");
2057 else if (rtype
->forward_declaration_type() != NULL
)
2059 // Go ahead and add the method in case we need to report
2060 // an error when we see the definition.
2061 rtype
->forward_declaration_type()->add_existing_method(ret
);
2064 go_error_at(type
->receiver()->location(),
2065 ("invalid receiver type "
2066 "(receiver must be a named type)"));
2069 else if (!type
->is_method())
2071 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
2072 if (!ret
->is_function() || ret
->func_value() != function
)
2074 // Redefinition error. Invent a name to avoid knockon
2076 std::string
rname(this->redefined_function_name());
2077 ret
= this->package_
->bindings()->add_function(rname
, NULL
, function
);
2082 if (!add_method_to_type
)
2083 ret
= Named_object::make_function(name
, NULL
, function
);
2086 go_assert(at_top_level
);
2087 Type
* rtype
= type
->receiver()->type();
2089 while (rtype
->named_type() != NULL
2090 && rtype
->named_type()->is_alias())
2091 rtype
= rtype
->named_type()->real_type()->forwarded();
2093 // We want to look through the pointer created by the
2094 // parser, without getting an error if the type is not yet
2096 if (rtype
->classification() == Type::TYPE_POINTER
)
2097 rtype
= rtype
->points_to();
2099 while (rtype
->named_type() != NULL
2100 && rtype
->named_type()->is_alias())
2101 rtype
= rtype
->named_type()->real_type()->forwarded();
2103 if (rtype
->is_error_type())
2104 ret
= Named_object::make_function(name
, NULL
, function
);
2105 else if (rtype
->named_type() != NULL
)
2107 if (rtype
->named_type()->named_object()->package() != NULL
)
2109 go_error_at(type
->receiver()->location(),
2110 "may not define methods on non-local type");
2111 ret
= Named_object::make_function(name
, NULL
, function
);
2115 ret
= rtype
->named_type()->add_method(name
, function
);
2116 if (!ret
->is_function())
2118 // Redefinition error.
2119 ret
= Named_object::make_function(name
, NULL
, function
);
2123 else if (rtype
->forward_declaration_type() != NULL
)
2125 Named_object
* type_no
=
2126 rtype
->forward_declaration_type()->named_object();
2127 if (type_no
->is_unknown())
2129 // If we are seeing methods it really must be a
2130 // type. Declare it as such. An alternative would
2131 // be to support lists of methods for unknown
2132 // expressions. Either way the error messages if
2133 // this is not a type are going to get confusing.
2134 Named_object
* declared
=
2135 this->declare_package_type(type_no
->name(),
2136 type_no
->location());
2138 == type_no
->unknown_value()->real_named_object());
2140 ret
= rtype
->forward_declaration_type()->add_method(name
,
2145 go_error_at(type
->receiver()->location(),
2146 ("invalid receiver type (receiver must "
2147 "be a named type)"));
2148 ret
= Named_object::make_function(name
, NULL
, function
);
2151 this->package_
->bindings()->add_method(ret
);
2154 this->functions_
.resize(this->functions_
.size() + 1);
2155 Open_function
& of(this->functions_
.back());
2157 of
.blocks
.push_back(block
);
2161 this->init_functions_
.push_back(ret
);
2162 this->need_init_fn_
= true;
2168 // Finish compiling a function.
2171 Gogo::finish_function(Location location
)
2173 this->finish_block(location
);
2174 go_assert(this->functions_
.back().blocks
.empty());
2175 this->functions_
.pop_back();
2178 // Return the current function.
2181 Gogo::current_function() const
2183 go_assert(!this->functions_
.empty());
2184 return this->functions_
.back().function
;
2187 // Start a new block.
2190 Gogo::start_block(Location location
)
2192 go_assert(!this->functions_
.empty());
2193 Block
* block
= new Block(this->current_block(), location
);
2194 this->functions_
.back().blocks
.push_back(block
);
2200 Gogo::finish_block(Location location
)
2202 go_assert(!this->functions_
.empty());
2203 go_assert(!this->functions_
.back().blocks
.empty());
2204 Block
* block
= this->functions_
.back().blocks
.back();
2205 this->functions_
.back().blocks
.pop_back();
2206 block
->set_end_location(location
);
2210 // Add an erroneous name.
2213 Gogo::add_erroneous_name(const std::string
& name
)
2215 return this->package_
->bindings()->add_erroneous_name(name
);
2218 // Add an unknown name.
2221 Gogo::add_unknown_name(const std::string
& name
, Location location
)
2223 return this->package_
->bindings()->add_unknown_name(name
, location
);
2226 // Declare a function.
2229 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
2232 if (!type
->is_method())
2233 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
2237 // We don't bother to add this to the list of global
2239 Type
* rtype
= type
->receiver()->type();
2241 while (rtype
->named_type() != NULL
2242 && rtype
->named_type()->is_alias())
2243 rtype
= rtype
->named_type()->real_type()->forwarded();
2245 // We want to look through the pointer created by the
2246 // parser, without getting an error if the type is not yet
2248 if (rtype
->classification() == Type::TYPE_POINTER
)
2249 rtype
= rtype
->points_to();
2251 while (rtype
->named_type() != NULL
2252 && rtype
->named_type()->is_alias())
2253 rtype
= rtype
->named_type()->real_type()->forwarded();
2255 if (rtype
->is_error_type())
2257 else if (rtype
->named_type() != NULL
)
2258 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
2260 else if (rtype
->forward_declaration_type() != NULL
)
2262 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
2263 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
2267 go_error_at(type
->receiver()->location(),
2268 "invalid receiver type (receiver must be a named type)");
2269 return Named_object::make_erroneous_name(name
);
2274 // Add a label definition.
2277 Gogo::add_label_definition(const std::string
& label_name
,
2280 go_assert(!this->functions_
.empty());
2281 Function
* func
= this->functions_
.back().function
->func_value();
2282 Label
* label
= func
->add_label_definition(this, label_name
, location
);
2283 this->add_statement(Statement::make_label_statement(label
, location
));
2287 // Add a label reference.
2290 Gogo::add_label_reference(const std::string
& label_name
,
2291 Location location
, bool issue_goto_errors
)
2293 go_assert(!this->functions_
.empty());
2294 Function
* func
= this->functions_
.back().function
->func_value();
2295 return func
->add_label_reference(this, label_name
, location
,
2299 // Return the current binding state.
2302 Gogo::bindings_snapshot(Location location
)
2304 return new Bindings_snapshot(this->current_block(), location
);
2310 Gogo::add_statement(Statement
* statement
)
2312 go_assert(!this->functions_
.empty()
2313 && !this->functions_
.back().blocks
.empty());
2314 this->functions_
.back().blocks
.back()->add_statement(statement
);
2320 Gogo::add_block(Block
* block
, Location location
)
2322 go_assert(!this->functions_
.empty()
2323 && !this->functions_
.back().blocks
.empty());
2324 Statement
* statement
= Statement::make_block_statement(block
, location
);
2325 this->functions_
.back().blocks
.back()->add_statement(statement
);
2331 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2334 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2340 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2342 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2344 if (!this->in_global_scope() && no
->is_type())
2346 Named_object
* f
= this->functions_
.back().function
;
2348 if (f
->is_function())
2349 index
= f
->func_value()->new_local_type_index();
2352 no
->type_value()->set_in_function(f
, index
);
2356 // Add a named type.
2359 Gogo::add_named_type(Named_type
* type
)
2361 go_assert(this->in_global_scope());
2362 this->current_bindings()->add_named_type(type
);
2368 Gogo::declare_type(const std::string
& name
, Location location
)
2370 Bindings
* bindings
= this->current_bindings();
2371 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2372 if (!this->in_global_scope() && no
->is_type_declaration())
2374 Named_object
* f
= this->functions_
.back().function
;
2376 if (f
->is_function())
2377 index
= f
->func_value()->new_local_type_index();
2380 no
->type_declaration_value()->set_in_function(f
, index
);
2385 // Declare a type at the package level.
2388 Gogo::declare_package_type(const std::string
& name
, Location location
)
2390 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2393 // Declare a function at the package level.
2396 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2399 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2403 // Add a function declaration to the list of functions we may want to
2407 Gogo::add_imported_inlinable_function(Named_object
* no
)
2409 go_assert(no
->is_function_declaration());
2410 Function_declaration
* fd
= no
->func_declaration_value();
2411 if (fd
->is_on_inlinable_list())
2413 this->imported_inlinable_functions_
.push_back(no
);
2414 fd
->set_is_on_inlinable_list();
2417 // Define a type which was already declared.
2420 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2422 this->current_bindings()->define_type(no
, type
);
2428 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2430 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2433 // In a function the middle-end wants to see a DECL_EXPR node.
2435 && no
->is_variable()
2436 && !no
->var_value()->is_parameter()
2437 && !this->functions_
.empty())
2438 this->add_statement(Statement::make_variable_declaration(no
));
2444 Gogo::rename_if_empty(std::string
* pname
, const char* tag
, unsigned* count
)
2446 if (pname
->empty() || Gogo::is_sink_name(*pname
))
2449 go_assert(strlen(tag
) < 10);
2450 snprintf(buf
, sizeof buf
, "%s.%u", tag
, *count
);
2457 // Add a sink--a reference to the blank identifier _.
2462 return Named_object::make_sink();
2465 // Add a named object for a dot import.
2468 Gogo::add_dot_import_object(Named_object
* no
)
2470 // If the name already exists, then it was defined in some file seen
2471 // earlier. If the earlier name is just a declaration, don't add
2472 // this name, because that will cause the previous declaration to
2473 // merge to this imported name, which should not happen. Just add
2474 // this name to the list of file block names to get appropriate
2475 // errors if we see a later definition.
2476 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2477 if (e
!= NULL
&& e
->package() == NULL
)
2479 if (e
->is_unknown())
2481 if (e
->package() == NULL
2482 && (e
->is_type_declaration()
2483 || e
->is_function_declaration()
2484 || e
->is_unknown()))
2486 this->add_file_block_name(no
->name(), no
->location());
2491 this->current_bindings()->add_named_object(no
);
2494 // Add a linkname. This implements the go:linkname compiler directive.
2495 // We only support this for functions and function declarations.
2498 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2499 const std::string
& ext_name
, Location loc
)
2502 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2505 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2506 else if (no
->is_function())
2508 if (ext_name
.empty())
2509 no
->func_value()->set_is_exported_by_linkname();
2511 no
->func_value()->set_asm_name(ext_name
);
2513 else if (no
->is_function_declaration())
2515 if (ext_name
.empty())
2517 ("%<//go:linkname%> missing external name "
2518 "for declaration of %s"),
2521 no
->func_declaration_value()->set_asm_name(ext_name
);
2525 ("%s is not a function; "
2526 "%<//go:linkname%> is only supported for functions"),
2530 // Mark all local variables used. This is used when some types of
2531 // parse error occur.
2534 Gogo::mark_locals_used()
2536 for (Open_functions::iterator pf
= this->functions_
.begin();
2537 pf
!= this->functions_
.end();
2540 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2541 pb
!= pf
->blocks
.end();
2543 (*pb
)->bindings()->mark_locals_used();
2547 // Record that we've seen an interface type.
2550 Gogo::record_interface_type(Interface_type
* itype
)
2552 this->interface_types_
.push_back(itype
);
2555 // Define the global names. We do this only after parsing all the
2556 // input files, because the program might define the global names
2560 Gogo::define_global_names()
2562 if (this->is_main_package())
2564 // Every Go program has to import the runtime package, so that
2565 // it is properly initialized. We can't use
2566 // predeclared_location here as it will cause runtime functions
2567 // to appear to be builtin functions.
2568 this->import_package("runtime", "_", false, false,
2569 this->package_
->location());
2572 for (Bindings::const_declarations_iterator p
=
2573 this->globals_
->begin_declarations();
2574 p
!= this->globals_
->end_declarations();
2577 Named_object
* global_no
= p
->second
;
2578 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2579 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2583 if (no
->is_type_declaration())
2585 if (global_no
->is_type())
2587 if (no
->type_declaration_value()->has_methods())
2589 for (std::vector
<Named_object
*>::const_iterator pm
=
2590 no
->type_declaration_value()->methods()->begin();
2591 pm
!= no
->type_declaration_value()->methods()->end();
2593 go_error_at((*pm
)->location(),
2594 "may not define methods on non-local type");
2596 no
->set_type_value(global_no
->type_value());
2600 go_error_at(no
->location(), "expected type");
2601 Type
* errtype
= Type::make_error_type();
2603 Named_object::make_type("erroneous_type", NULL
, errtype
,
2604 Linemap::predeclared_location());
2605 no
->set_type_value(err
->type_value());
2608 else if (no
->is_unknown())
2609 no
->unknown_value()->set_real_named_object(global_no
);
2612 // Give an error if any name is defined in both the package block
2613 // and the file block. For example, this can happen if one file
2614 // imports "fmt" and another file defines a global variable fmt.
2615 for (Bindings::const_declarations_iterator p
=
2616 this->package_
->bindings()->begin_declarations();
2617 p
!= this->package_
->bindings()->end_declarations();
2620 if (p
->second
->is_unknown()
2621 && p
->second
->unknown_value()->real_named_object() == NULL
)
2623 // No point in warning about an undefined name, as we will
2624 // get other errors later anyhow.
2627 File_block_names::const_iterator pf
=
2628 this->file_block_names_
.find(p
->second
->name());
2629 if (pf
!= this->file_block_names_
.end())
2631 std::string n
= p
->second
->message_name();
2632 go_error_at(p
->second
->location(),
2633 "%qs defined as both imported name and global name",
2635 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2638 // No package scope identifier may be named "init".
2639 if (!p
->second
->is_function()
2640 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2642 go_error_at(p
->second
->location(),
2643 "cannot declare init - must be func");
2648 // Clear out names in file scope.
2651 Gogo::clear_file_scope()
2653 this->package_
->bindings()->clear_file_scope(this);
2655 // Warn about packages which were imported but not used.
2656 bool quiet
= saw_errors();
2657 for (Packages::iterator p
= this->packages_
.begin();
2658 p
!= this->packages_
.end();
2661 Package
* package
= p
->second
;
2662 if (package
!= this->package_
&& !quiet
)
2664 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2665 p1
!= package
->aliases().end();
2668 if (!p1
->second
->used())
2670 // Give a more refined error message if the alias name is known.
2671 std::string pkg_name
= package
->package_name();
2672 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2674 go_error_at(p1
->second
->location(),
2675 "imported and not used: %s as %s",
2676 Gogo::message_name(pkg_name
).c_str(),
2677 Gogo::message_name(p1
->first
).c_str());
2680 go_error_at(p1
->second
->location(),
2681 "imported and not used: %s",
2682 Gogo::message_name(pkg_name
).c_str());
2686 package
->clear_used();
2689 this->current_file_imported_unsafe_
= false;
2690 this->current_file_imported_embed_
= false;
2693 // Queue up a type-specific hash function for later writing. These
2694 // are written out in write_specific_type_functions, called after the
2695 // parse tree is lowered.
2698 Gogo::queue_hash_function(Type
* type
, int64_t size
, Backend_name
* bname
,
2699 Function_type
* hash_fntype
)
2701 go_assert(!this->specific_type_functions_are_written_
);
2702 go_assert(!this->in_global_scope());
2703 Specific_type_function::Specific_type_function_kind kind
=
2704 Specific_type_function::SPECIFIC_HASH
;
2705 Specific_type_function
* tsf
= new Specific_type_function(type
, NULL
, size
,
2708 this->specific_type_functions_
.push_back(tsf
);
2711 // Queue up a type-specific equal function for later writing. These
2712 // are written out in write_specific_type_functions, called after the
2713 // parse tree is lowered.
2716 Gogo::queue_equal_function(Type
* type
, Named_type
* name
, int64_t size
,
2717 Backend_name
* bname
, Function_type
* equal_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_EQUAL
;
2723 Specific_type_function
* tsf
= new Specific_type_function(type
, name
, size
,
2726 this->specific_type_functions_
.push_back(tsf
);
2729 // Look for types which need specific hash or equality functions.
2731 class Specific_type_functions
: public Traverse
2734 Specific_type_functions(Gogo
* gogo
)
2735 : Traverse(traverse_types
),
2747 Specific_type_functions::type(Type
* t
)
2749 switch (t
->classification())
2751 case Type::TYPE_NAMED
:
2753 Named_type
* nt
= t
->named_type();
2755 return TRAVERSE_CONTINUE
;
2756 if (t
->needs_specific_type_functions(this->gogo_
))
2757 t
->equal_function(this->gogo_
, nt
, NULL
);
2759 // If this is a struct type, we don't want to make functions
2760 // for the unnamed struct.
2761 Type
* rt
= nt
->real_type();
2762 if (rt
->struct_type() == NULL
)
2764 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2765 return TRAVERSE_EXIT
;
2769 // If this type is defined in another package, then we don't
2770 // need to worry about the unexported fields.
2771 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2772 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2773 for (Struct_field_list::const_iterator p
= fields
->begin();
2777 if (is_defined_elsewhere
2778 && Gogo::is_hidden_name(p
->field_name()))
2780 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2781 return TRAVERSE_EXIT
;
2785 return TRAVERSE_SKIP_COMPONENTS
;
2788 case Type::TYPE_STRUCT
:
2789 case Type::TYPE_ARRAY
:
2790 if (t
->needs_specific_type_functions(this->gogo_
))
2791 t
->equal_function(this->gogo_
, NULL
, NULL
);
2794 case Type::TYPE_MAP
:
2796 Type
* key_type
= t
->map_type()->key_type()->unalias();
2797 if (key_type
->needs_specific_type_functions(this->gogo_
))
2798 key_type
->hash_function(this->gogo_
, NULL
);
2806 return TRAVERSE_CONTINUE
;
2809 // Write out type specific functions.
2812 Gogo::write_specific_type_functions()
2814 Specific_type_functions
stf(this);
2815 this->traverse(&stf
);
2817 while (!this->specific_type_functions_
.empty())
2819 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2820 this->specific_type_functions_
.pop_back();
2821 if (tsf
->kind
== Specific_type_function::SPECIFIC_HASH
)
2822 tsf
->type
->write_hash_function(this, tsf
->size
, &tsf
->bname
,
2825 tsf
->type
->write_equal_function(this, tsf
->name
, tsf
->size
,
2826 &tsf
->bname
, tsf
->fntype
);
2829 this->specific_type_functions_are_written_
= true;
2832 // Traverse the tree.
2835 Gogo::traverse(Traverse
* traverse
)
2837 // Traverse the current package first for consistency. The other
2838 // packages will only contain imported types, constants, and
2840 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2842 for (Packages::const_iterator p
= this->packages_
.begin();
2843 p
!= this->packages_
.end();
2846 if (p
->second
!= this->package_
)
2848 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2854 // Add a type to verify. This is used for types of sink variables, in
2855 // order to give appropriate error messages.
2858 Gogo::add_type_to_verify(Type
* type
)
2860 this->verify_types_
.push_back(type
);
2863 // Traversal class used to verify types.
2865 class Verify_types
: public Traverse
2869 : Traverse(traverse_types
)
2876 // Verify that a type is correct.
2879 Verify_types::type(Type
* t
)
2882 return TRAVERSE_SKIP_COMPONENTS
;
2883 return TRAVERSE_CONTINUE
;
2886 // Verify that all types are correct.
2889 Gogo::verify_types()
2891 Verify_types traverse
;
2892 this->traverse(&traverse
);
2894 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2895 p
!= this->verify_types_
.end();
2898 this->verify_types_
.clear();
2901 // Traversal class used to lower parse tree.
2903 class Lower_parse_tree
: public Traverse
2906 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2907 : Traverse(traverse_variables
2908 | traverse_constants
2909 | traverse_functions
2910 | traverse_statements
2911 | traverse_expressions
),
2912 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2916 set_inserter(const Statement_inserter
* inserter
)
2917 { this->inserter_
= *inserter
; }
2920 variable(Named_object
*);
2923 constant(Named_object
*, bool);
2926 function(Named_object
*);
2929 statement(Block
*, size_t* pindex
, Statement
*);
2932 expression(Expression
**);
2937 // The function we are traversing.
2938 Named_object
* function_
;
2939 // Value to use for the predeclared constant iota.
2941 // Current statement inserter for use by expressions.
2942 Statement_inserter inserter_
;
2948 Lower_parse_tree::variable(Named_object
* no
)
2950 if (!no
->is_variable())
2951 return TRAVERSE_CONTINUE
;
2953 if (no
->is_variable() && no
->var_value()->is_global())
2955 // Global variables can have loops in their initialization
2956 // expressions. This is handled in lower_init_expression.
2957 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2959 return TRAVERSE_CONTINUE
;
2962 // This is a local variable. We are going to return
2963 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2964 // initialization expression when we reach the variable declaration
2965 // statement. However, that means that we need to traverse the type
2967 if (no
->var_value()->has_type())
2969 Type
* type
= no
->var_value()->type();
2972 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2973 return TRAVERSE_EXIT
;
2976 go_assert(!no
->var_value()->has_pre_init());
2978 return TRAVERSE_SKIP_COMPONENTS
;
2981 // Lower constants. We handle constants specially so that we can set
2982 // the right value for the predeclared constant iota. This works in
2983 // conjunction with the way we lower Const_expression objects.
2986 Lower_parse_tree::constant(Named_object
* no
, bool)
2988 Named_constant
* nc
= no
->const_value();
2990 // Don't get into trouble if the constant's initializer expression
2991 // refers to the constant itself.
2993 return TRAVERSE_CONTINUE
;
2996 go_assert(this->iota_value_
== -1);
2997 this->iota_value_
= nc
->iota_value();
2998 nc
->traverse_expression(this);
2999 this->iota_value_
= -1;
3001 nc
->clear_lowering();
3003 // We will traverse the expression a second time, but that will be
3006 return TRAVERSE_CONTINUE
;
3009 // Lower the body of a function, and set the closure type. Record the
3010 // function while lowering it, so that we can pass it down when
3011 // lowering an expression.
3014 Lower_parse_tree::function(Named_object
* no
)
3016 no
->func_value()->set_closure_type();
3018 go_assert(this->function_
== NULL
);
3019 this->function_
= no
;
3020 int t
= no
->func_value()->traverse(this);
3021 this->function_
= NULL
;
3023 if (t
== TRAVERSE_EXIT
)
3025 return TRAVERSE_SKIP_COMPONENTS
;
3028 // Lower statement parse trees.
3031 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3033 // Because we explicitly traverse the statement's contents
3034 // ourselves, we want to skip block statements here. There is
3035 // nothing to lower in a block statement.
3036 if (sorig
->is_block_statement())
3037 return TRAVERSE_CONTINUE
;
3039 Statement_inserter
hold_inserter(this->inserter_
);
3040 this->inserter_
= Statement_inserter(block
, pindex
);
3042 // Lower the expressions first.
3043 int t
= sorig
->traverse_contents(this);
3044 if (t
== TRAVERSE_EXIT
)
3046 this->inserter_
= hold_inserter
;
3050 // Keep lowering until nothing changes.
3051 Statement
* s
= sorig
;
3054 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
3059 t
= s
->traverse_contents(this);
3060 if (t
== TRAVERSE_EXIT
)
3062 this->inserter_
= hold_inserter
;
3068 block
->replace_statement(*pindex
, s
);
3070 this->inserter_
= hold_inserter
;
3071 return TRAVERSE_SKIP_COMPONENTS
;
3074 // Lower expression parse trees.
3077 Lower_parse_tree::expression(Expression
** pexpr
)
3079 // We have to lower all subexpressions first, so that we can get
3080 // their type if necessary. This is awkward, because we don't have
3081 // a postorder traversal pass.
3082 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3083 return TRAVERSE_EXIT
;
3084 // Keep lowering until nothing changes.
3087 Expression
* e
= *pexpr
;
3088 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
3089 &this->inserter_
, this->iota_value_
);
3092 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3093 return TRAVERSE_EXIT
;
3097 // Lower the type of this expression before the parent looks at it,
3098 // in case the type contains an array that has expressions in its
3099 // length. Skip an Unknown_expression, as at this point that means
3100 // a composite literal key that does not have a type.
3101 if ((*pexpr
)->unknown_expression() == NULL
)
3102 Type::traverse((*pexpr
)->type(), this);
3104 return TRAVERSE_SKIP_COMPONENTS
;
3107 // Lower the parse tree. This is called after the parse is complete,
3108 // when all names should be resolved.
3111 Gogo::lower_parse_tree()
3113 Lower_parse_tree
lower_parse_tree(this, NULL
);
3114 this->traverse(&lower_parse_tree
);
3116 // If we found any functions defined in other packages that are
3117 // inlinables, import their bodies and turn them into functions.
3119 // Note that as we import inlinable functions we may find more
3120 // inlinable functions, so don't use an iterator.
3121 for (size_t i
= 0; i
< this->imported_inlinable_functions_
.size(); i
++)
3123 Named_object
* no
= this->imported_inlinable_functions_
[i
];
3124 no
->func_declaration_value()->import_function_body(this, no
);
3127 // There might be type definitions that involve expressions such as the
3128 // array length. Make sure to lower these expressions as well. Otherwise,
3129 // errors hidden within a type can introduce unexpected errors into later
3131 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
3132 p
!= this->verify_types_
.end();
3134 Type::traverse(*p
, &lower_parse_tree
);
3140 Gogo::lower_block(Named_object
* function
, Block
* block
)
3142 Lower_parse_tree
lower_parse_tree(this, function
);
3143 block
->traverse(&lower_parse_tree
);
3146 // Lower an expression. INSERTER may be NULL, in which case the
3147 // expression had better not need to create any temporaries.
3150 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
3153 Lower_parse_tree
lower_parse_tree(this, function
);
3154 if (inserter
!= NULL
)
3155 lower_parse_tree
.set_inserter(inserter
);
3156 lower_parse_tree
.expression(pexpr
);
3159 // Lower a constant. This is called when lowering a reference to a
3160 // constant. We have to make sure that the constant has already been
3164 Gogo::lower_constant(Named_object
* no
)
3166 go_assert(no
->is_const());
3167 Lower_parse_tree
lower(this, NULL
);
3168 lower
.constant(no
, false);
3171 // Make implicit type conversions explicit. Currently only does for
3172 // interface conversions, so the escape analysis can see them and
3175 class Add_conversions
: public Traverse
3179 : Traverse(traverse_statements
3180 | traverse_expressions
)
3184 statement(Block
*, size_t* pindex
, Statement
*);
3187 expression(Expression
**);
3190 // Add explicit conversions in a statement.
3193 Add_conversions::statement(Block
*, size_t*, Statement
* sorig
)
3195 sorig
->add_conversions();
3196 return TRAVERSE_CONTINUE
;
3199 // Add explicit conversions in an expression.
3202 Add_conversions::expression(Expression
** pexpr
)
3204 (*pexpr
)->add_conversions();
3205 return TRAVERSE_CONTINUE
;
3209 Gogo::add_conversions()
3211 Add_conversions add_conversions
;
3212 this->traverse(&add_conversions
);
3216 Gogo::add_conversions_in_block(Block
*b
)
3218 Add_conversions add_conversions
;
3219 b
->traverse(&add_conversions
);
3222 // Traversal class for simple deadcode elimination.
3224 class Remove_deadcode
: public Traverse
3228 : Traverse(traverse_statements
3229 | traverse_expressions
)
3233 statement(Block
*, size_t* pindex
, Statement
*);
3236 expression(Expression
**);
3239 // Remove deadcode in a statement.
3242 Remove_deadcode::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3244 Location loc
= sorig
->location();
3245 If_statement
* ifs
= sorig
->if_statement();
3248 // Remove the dead branch of an if statement.
3250 if (ifs
->condition()->boolean_constant_value(&bval
))
3254 s
= Statement::make_block_statement(ifs
->then_block(),
3257 if (ifs
->else_block() != NULL
)
3258 s
= Statement::make_block_statement(ifs
->else_block(),
3261 // Make a dummy statement.
3262 s
= Statement::make_statement(Expression::make_boolean(false, loc
),
3265 block
->replace_statement(*pindex
, s
);
3268 return TRAVERSE_CONTINUE
;
3271 // Remove deadcode in an expression.
3274 Remove_deadcode::expression(Expression
** pexpr
)
3276 // Discard the right arm of a shortcut expression of constant value.
3277 Binary_expression
* be
= (*pexpr
)->binary_expression();
3280 && be
->boolean_constant_value(&bval
)
3281 && (be
->op() == OPERATOR_ANDAND
3282 || be
->op() == OPERATOR_OROR
))
3284 *pexpr
= Expression::make_boolean(bval
, be
->location());
3285 Type_context
context(NULL
, false);
3286 (*pexpr
)->determine_type(&context
);
3288 return TRAVERSE_CONTINUE
;
3294 Gogo::remove_deadcode()
3296 Remove_deadcode remove_deadcode
;
3297 this->traverse(&remove_deadcode
);
3300 // Traverse the tree to create function descriptors as needed.
3302 class Create_function_descriptors
: public Traverse
3305 Create_function_descriptors(Gogo
* gogo
)
3306 : Traverse(traverse_functions
| traverse_expressions
),
3311 function(Named_object
*);
3314 expression(Expression
**);
3317 skip_descriptor(Gogo
* gogo
, const Named_object
*);
3323 // Create a descriptor for every top-level exported function and every
3324 // function referenced by an inline function.
3327 Create_function_descriptors::function(Named_object
* no
)
3329 if (Create_function_descriptors::skip_descriptor(this->gogo_
, no
))
3330 return TRAVERSE_CONTINUE
;
3332 if (no
->is_function()
3333 && no
->func_value()->enclosing() == NULL
3334 && !no
->func_value()->is_method()
3335 && ((!Gogo::is_hidden_name(no
->name())
3336 && !Gogo::is_thunk(no
))
3337 || no
->func_value()->is_referenced_by_inline()))
3338 no
->func_value()->descriptor(this->gogo_
, no
);
3340 return TRAVERSE_CONTINUE
;
3343 // If we see a function referenced in any way other than calling it,
3344 // create a descriptor for it.
3347 Create_function_descriptors::expression(Expression
** pexpr
)
3349 Expression
* expr
= *pexpr
;
3351 Func_expression
* fe
= expr
->func_expression();
3354 // We would not get here for a call to this function, so this is
3355 // a reference to a function other than calling it. We need a
3357 if (fe
->closure() != NULL
)
3358 return TRAVERSE_CONTINUE
;
3359 Named_object
* no
= fe
->named_object();
3360 if (no
->is_function() && !no
->func_value()->is_method())
3361 no
->func_value()->descriptor(this->gogo_
, no
);
3362 else if (no
->is_function_declaration()
3363 && !no
->func_declaration_value()->type()->is_method()
3364 && !Linemap::is_predeclared_location(no
->location()))
3365 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
3366 return TRAVERSE_CONTINUE
;
3369 Bound_method_expression
* bme
= expr
->bound_method_expression();
3372 // We would not get here for a call to this method, so this is a
3373 // method value. We need to create a thunk.
3374 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
3376 return TRAVERSE_CONTINUE
;
3379 Interface_field_reference_expression
* ifre
=
3380 expr
->interface_field_reference_expression();
3383 // We would not get here for a call to this interface method, so
3384 // this is a method value. We need to create a thunk.
3385 Interface_type
* type
= ifre
->expr()->type()->interface_type();
3387 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
3389 return TRAVERSE_CONTINUE
;
3392 Call_expression
* ce
= expr
->call_expression();
3395 Expression
* fn
= ce
->fn();
3396 if (fn
->func_expression() != NULL
3397 || fn
->bound_method_expression() != NULL
3398 || fn
->interface_field_reference_expression() != NULL
)
3400 // Traverse the arguments but not the function.
3401 Expression_list
* args
= ce
->args();
3404 if (args
->traverse(this) == TRAVERSE_EXIT
)
3405 return TRAVERSE_EXIT
;
3408 // Traverse the subexpressions of the function, if any.
3409 if (fn
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3410 return TRAVERSE_EXIT
;
3412 return TRAVERSE_SKIP_COMPONENTS
;
3416 return TRAVERSE_CONTINUE
;
3419 // The gc compiler has some special cases that it always compiles as
3420 // intrinsics. For those we don't want to generate a function
3421 // descriptor, as there will be no code for it to refer to.
3424 Create_function_descriptors::skip_descriptor(Gogo
* gogo
,
3425 const Named_object
* no
)
3427 const std::string
& pkgpath(no
->package() == NULL
3429 : no
->package()->pkgpath());
3431 // internal/abi is the standard library package,
3432 // bootstrap/internal/abi is the name used when bootstrapping the gc
3435 return ((pkgpath
== "internal/abi"
3436 || pkgpath
== "bootstrap/internal/abi")
3437 && (no
->name() == "FuncPCABI0"
3438 || no
->name() == "FuncPCABIInternal"));
3441 // Create function descriptors as needed. We need a function
3442 // descriptor for all exported functions and for all functions that
3443 // are referenced without being called.
3446 Gogo::create_function_descriptors()
3448 // Create a function descriptor for any exported function that is
3449 // declared in this package. This is so that we have a descriptor
3450 // for functions written in assembly. Gather the descriptors first
3451 // so that we don't add declarations while looping over them.
3452 std::vector
<Named_object
*> fndecls
;
3453 Bindings
* b
= this->package_
->bindings();
3454 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
3455 p
!= b
->end_declarations();
3458 Named_object
* no
= p
->second
;
3459 if (no
->is_function_declaration()
3460 && !no
->func_declaration_value()->type()->is_method()
3461 && !Linemap::is_predeclared_location(no
->location())
3462 && !Gogo::is_hidden_name(no
->name())
3463 && !Create_function_descriptors::skip_descriptor(this, no
))
3464 fndecls
.push_back(no
);
3466 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
3469 (*p
)->func_declaration_value()->descriptor(this, *p
);
3472 Create_function_descriptors
cfd(this);
3473 this->traverse(&cfd
);
3476 // Finalize the methods of an interface type.
3479 Finalize_methods::type(Type
* t
)
3481 // Check the classification so that we don't finalize the methods
3482 // twice for a named interface type.
3483 switch (t
->classification())
3485 case Type::TYPE_INTERFACE
:
3486 t
->interface_type()->finalize_methods();
3489 case Type::TYPE_NAMED
:
3491 Named_type
* nt
= t
->named_type();
3494 return TRAVERSE_CONTINUE
;
3496 Type
* rt
= nt
->real_type();
3497 if (rt
->classification() != Type::TYPE_STRUCT
)
3499 // Finalize the methods of the real type first.
3500 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
3501 return TRAVERSE_EXIT
;
3503 // Finalize the methods of this type.
3504 nt
->finalize_methods(this->gogo_
);
3508 // We don't want to finalize the methods of a named struct
3509 // type, as the methods should be attached to the named
3510 // type, not the struct type. We just want to finalize
3513 // It is possible that a field type refers indirectly to
3514 // this type, such as via a field with function type with
3515 // an argument or result whose type is this type. To
3516 // avoid the cycle, first finalize the methods of any
3517 // embedded types, which are the only types we need to
3518 // know to finalize the methods of this type.
3519 const Struct_field_list
* fields
= rt
->struct_type()->fields();
3522 for (Struct_field_list::const_iterator pf
= fields
->begin();
3523 pf
!= fields
->end();
3526 if (pf
->is_anonymous())
3528 if (Type::traverse(pf
->type(), this) == TRAVERSE_EXIT
)
3529 return TRAVERSE_EXIT
;
3534 // Finalize the methods of this type.
3535 nt
->finalize_methods(this->gogo_
);
3537 // Finalize all the struct fields.
3538 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3539 return TRAVERSE_EXIT
;
3542 // If this type is defined in a different package, then finalize the
3543 // types of all the methods, since we won't see them otherwise.
3544 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
3546 const Methods
* methods
= nt
->methods();
3547 for (Methods::const_iterator p
= methods
->begin();
3548 p
!= methods
->end();
3551 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
3552 return TRAVERSE_EXIT
;
3556 // Finalize the types of all methods that are declared but not
3557 // defined, since we won't see the declarations otherwise.
3558 if (nt
->named_object()->package() == NULL
3559 && nt
->local_methods() != NULL
)
3561 const Bindings
* methods
= nt
->local_methods();
3562 for (Bindings::const_declarations_iterator p
=
3563 methods
->begin_declarations();
3564 p
!= methods
->end_declarations();
3567 if (p
->second
->is_function_declaration())
3569 Type
* mt
= p
->second
->func_declaration_value()->type();
3570 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3571 return TRAVERSE_EXIT
;
3576 return TRAVERSE_SKIP_COMPONENTS
;
3579 case Type::TYPE_STRUCT
:
3580 // Traverse the field types first in case there is an embedded
3581 // field with methods that the struct should inherit.
3582 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3583 return TRAVERSE_EXIT
;
3584 t
->struct_type()->finalize_methods(this->gogo_
);
3585 return TRAVERSE_SKIP_COMPONENTS
;
3591 return TRAVERSE_CONTINUE
;
3594 // Finalize method lists and build stub methods for types.
3597 Gogo::finalize_methods()
3599 Finalize_methods
finalize(this);
3600 this->traverse(&finalize
);
3603 // Finalize the method list for a type. This is called when a type is
3604 // parsed for an inlined function body, which happens after the
3605 // finalize_methods pass.
3608 Gogo::finalize_methods_for_type(Type
* type
)
3610 Finalize_methods
finalize(this);
3611 Type::traverse(type
, &finalize
);
3614 // Set types for unspecified variables and constants.
3617 Gogo::determine_types()
3619 Bindings
* bindings
= this->current_bindings();
3620 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3621 p
!= bindings
->end_definitions();
3624 if ((*p
)->is_function())
3625 (*p
)->func_value()->determine_types();
3626 else if ((*p
)->is_variable())
3627 (*p
)->var_value()->determine_type();
3628 else if ((*p
)->is_const())
3629 (*p
)->const_value()->determine_type();
3631 // See if a variable requires us to build an initialization
3632 // function. We know that we will see all global variables
3634 if (!this->need_init_fn_
&& (*p
)->is_variable())
3636 Variable
* variable
= (*p
)->var_value();
3638 // If this is a global variable which requires runtime
3639 // initialization, we need an initialization function.
3640 if (!variable
->is_global())
3642 else if (variable
->init() == NULL
)
3644 else if (variable
->type()->interface_type() != NULL
)
3645 this->need_init_fn_
= true;
3646 else if (variable
->init()->is_constant())
3648 else if (!variable
->init()->is_composite_literal())
3649 this->need_init_fn_
= true;
3650 else if (variable
->init()->is_nonconstant_composite_literal())
3651 this->need_init_fn_
= true;
3653 // If this is a global variable which holds a pointer value,
3654 // then we need an initialization function to register it as a
3656 if (variable
->is_global() && variable
->type()->has_pointer())
3657 this->need_init_fn_
= true;
3661 // Determine the types of constants in packages.
3662 for (Packages::const_iterator p
= this->packages_
.begin();
3663 p
!= this->packages_
.end();
3665 p
->second
->determine_types();
3668 // Traversal class used for type checking.
3670 class Check_types_traverse
: public Traverse
3673 Check_types_traverse(Gogo
* gogo
)
3674 : Traverse(traverse_variables
3675 | traverse_constants
3676 | traverse_functions
3677 | traverse_statements
3678 | traverse_expressions
),
3683 variable(Named_object
*);
3686 constant(Named_object
*, bool);
3689 function(Named_object
*);
3692 statement(Block
*, size_t* pindex
, Statement
*);
3695 expression(Expression
**);
3702 // Check that a variable initializer has the right type.
3705 Check_types_traverse::variable(Named_object
* named_object
)
3707 if (named_object
->is_variable())
3709 Variable
* var
= named_object
->var_value();
3711 // Give error if variable type is not defined.
3712 var
->type()->base();
3714 Expression
* init
= var
->init();
3717 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3720 go_error_at(var
->location(), "incompatible type in initialization");
3722 go_error_at(var
->location(),
3723 "incompatible type in initialization (%s)",
3725 init
= Expression::make_error(named_object
->location());
3728 else if (init
!= NULL
3729 && init
->func_expression() != NULL
)
3731 Named_object
* no
= init
->func_expression()->named_object();
3732 Function_type
* fntype
;
3733 if (no
->is_function())
3734 fntype
= no
->func_value()->type();
3735 else if (no
->is_function_declaration())
3736 fntype
= no
->func_declaration_value()->type();
3740 // Builtin functions cannot be used as function values for variable
3742 if (fntype
->is_builtin())
3744 go_error_at(init
->location(),
3745 "invalid use of special built-in function %qs; "
3747 no
->message_name().c_str());
3751 && !var
->is_global()
3752 && !var
->is_parameter()
3753 && !var
->is_receiver()
3754 && !var
->type()->is_error()
3755 && (init
== NULL
|| !init
->is_error_expression())
3756 && !Lex::is_invalid_identifier(named_object
->name()))
3757 go_error_at(var
->location(), "%qs declared but not used",
3758 named_object
->message_name().c_str());
3760 return TRAVERSE_CONTINUE
;
3763 // Check that a constant initializer has the right type.
3766 Check_types_traverse::constant(Named_object
* named_object
, bool)
3768 Named_constant
* constant
= named_object
->const_value();
3769 Type
* ctype
= constant
->type();
3770 if (ctype
->integer_type() == NULL
3771 && ctype
->float_type() == NULL
3772 && ctype
->complex_type() == NULL
3773 && !ctype
->is_boolean_type()
3774 && !ctype
->is_string_type())
3776 if (ctype
->is_nil_type())
3777 go_error_at(constant
->location(), "const initializer cannot be nil");
3778 else if (!ctype
->is_error())
3779 go_error_at(constant
->location(), "invalid constant type");
3780 constant
->set_error();
3782 else if (!constant
->expr()->is_constant())
3784 go_error_at(constant
->expr()->location(), "expression is not constant");
3785 constant
->set_error();
3787 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3790 go_error_at(constant
->location(),
3791 "initialization expression has wrong type");
3792 constant
->set_error();
3794 return TRAVERSE_CONTINUE
;
3797 // There are no types to check in a function, but this is where we
3798 // issue warnings about labels which are defined but not referenced.
3801 Check_types_traverse::function(Named_object
* no
)
3803 no
->func_value()->check_labels();
3804 return TRAVERSE_CONTINUE
;
3807 // Check that types are valid in a statement.
3810 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3812 s
->check_types(this->gogo_
);
3813 return TRAVERSE_CONTINUE
;
3816 // Check that types are valid in an expression.
3819 Check_types_traverse::expression(Expression
** expr
)
3821 (*expr
)->check_types(this->gogo_
);
3822 return TRAVERSE_CONTINUE
;
3825 // Check that types are valid.
3830 Check_types_traverse
traverse(this);
3831 this->traverse(&traverse
);
3833 Bindings
* bindings
= this->current_bindings();
3834 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3835 p
!= bindings
->end_declarations();
3838 // Also check the types in a function declaration's signature.
3839 Named_object
* no
= p
->second
;
3840 if (no
->is_function_declaration())
3841 no
->func_declaration_value()->check_types();
3845 // Check the types in a single block.
3848 Gogo::check_types_in_block(Block
* block
)
3850 Check_types_traverse
traverse(this);
3851 block
->traverse(&traverse
);
3854 // For each global variable defined in the current package, record the
3855 // set of variables that its initializer depends on. We do this after
3856 // lowering so that all unknown names are resolved to their final
3857 // locations. We do this before write barrier insertion because that
3858 // makes it harder to distinguish references from assignments in
3862 Gogo::record_global_init_refs()
3864 Bindings
* bindings
= this->package_
->bindings();
3865 for (Bindings::const_definitions_iterator pb
= bindings
->begin_definitions();
3866 pb
!= bindings
->end_definitions();
3869 Named_object
* no
= *pb
;
3870 if (!no
->is_variable())
3873 Variable
* var
= no
->var_value();
3874 go_assert(var
->is_global());
3876 Find_vars find_vars
;
3877 Expression
* init
= var
->init();
3879 Expression::traverse(&init
, &find_vars
);
3880 if (var
->has_pre_init())
3881 var
->preinit()->traverse(&find_vars
);
3882 Named_object
* dep
= this->var_depends_on(var
);
3885 Expression
* dinit
= dep
->var_value()->init();
3887 Expression::traverse(&dinit
, &find_vars
);
3888 if (dep
->var_value()->has_pre_init())
3889 dep
->var_value()->preinit()->traverse(&find_vars
);
3892 for (Find_vars::const_iterator pv
= find_vars
.begin();
3893 pv
!= find_vars
.end();
3895 var
->add_init_ref(*pv
);
3899 // A traversal class which finds all the expressions which must be
3900 // evaluated in order within a statement or larger expression. This
3901 // is used to implement the rules about order of evaluation.
3903 class Find_eval_ordering
: public Traverse
3906 typedef std::vector
<Expression
**> Expression_pointers
;
3909 Find_eval_ordering()
3910 : Traverse(traverse_blocks
3911 | traverse_statements
3912 | traverse_expressions
),
3918 { return this->exprs_
.size(); }
3920 typedef Expression_pointers::const_iterator const_iterator
;
3924 { return this->exprs_
.begin(); }
3928 { return this->exprs_
.end(); }
3933 { return TRAVERSE_SKIP_COMPONENTS
; }
3936 statement(Block
*, size_t*, Statement
*)
3937 { return TRAVERSE_SKIP_COMPONENTS
; }
3940 expression(Expression
**);
3943 // A list of pointers to expressions with side-effects.
3944 Expression_pointers exprs_
;
3947 // If an expression must be evaluated in order, put it on the list.
3950 Find_eval_ordering::expression(Expression
** expression_pointer
)
3952 Binary_expression
* binexp
= (*expression_pointer
)->binary_expression();
3954 && (binexp
->op() == OPERATOR_ANDAND
|| binexp
->op() == OPERATOR_OROR
))
3956 // Shortcut expressions may potentially have side effects which need
3957 // to be ordered, so add them to the list.
3958 // We don't order its subexpressions here since they may be evaluated
3959 // conditionally. This is handled in remove_shortcuts.
3960 this->exprs_
.push_back(expression_pointer
);
3961 return TRAVERSE_SKIP_COMPONENTS
;
3964 // We have to look at subexpressions before this one.
3965 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3966 return TRAVERSE_EXIT
;
3967 if ((*expression_pointer
)->must_eval_in_order())
3968 this->exprs_
.push_back(expression_pointer
);
3969 return TRAVERSE_SKIP_COMPONENTS
;
3972 // A traversal class for ordering evaluations.
3974 class Order_eval
: public Traverse
3977 Order_eval(Gogo
* gogo
)
3978 : Traverse(traverse_variables
3979 | traverse_statements
),
3984 variable(Named_object
*);
3987 statement(Block
*, size_t*, Statement
*);
3994 // Implement the order of evaluation rules for a statement.
3997 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* stmt
)
3999 // FIXME: This approach doesn't work for switch statements, because
4000 // we add the new statements before the whole switch when we need to
4001 // instead add them just before the switch expression. The right
4002 // fix is probably to lower switch statements with nonconstant cases
4003 // to a series of conditionals.
4004 if (stmt
->switch_statement() != NULL
)
4005 return TRAVERSE_CONTINUE
;
4007 Find_eval_ordering find_eval_ordering
;
4009 // If S is a variable declaration, then ordinary traversal won't do
4010 // anything. We want to explicitly traverse the initialization
4011 // expression if there is one.
4012 Variable_declaration_statement
* vds
= stmt
->variable_declaration_statement();
4013 Expression
* init
= NULL
;
4014 Expression
* orig_init
= NULL
;
4016 stmt
->traverse_contents(&find_eval_ordering
);
4019 init
= vds
->var()->var_value()->init();
4021 return TRAVERSE_CONTINUE
;
4024 // It might seem that this could be
4025 // init->traverse_subexpressions. Unfortunately that can fail
4028 // newvar, err := call(arg())
4029 // Here newvar will have an init of call result 0 of
4030 // call(arg()). If we only traverse subexpressions, we will
4031 // only find arg(), and we won't bother to move anything out.
4032 // Then we get to the assignment to err, we will traverse the
4033 // whole statement, and this time we will find both call() and
4034 // arg(), and so we will move them out. This will cause them to
4035 // be put into temporary variables before the assignment to err
4036 // but after the declaration of newvar. To avoid that problem,
4037 // we traverse the entire expression here.
4038 Expression::traverse(&init
, &find_eval_ordering
);
4041 size_t c
= find_eval_ordering
.size();
4043 return TRAVERSE_CONTINUE
;
4045 // If there is only one expression with a side-effect, we can
4046 // usually leave it in place.
4049 switch (stmt
->classification())
4051 case Statement::STATEMENT_ASSIGNMENT
:
4052 // For an assignment statement, we need to evaluate an
4053 // expression on the right hand side before we evaluate any
4054 // index expression on the left hand side, so for that case
4055 // we always move the expression. Otherwise we mishandle
4056 // m[0] = len(m) where m is a map.
4059 case Statement::STATEMENT_EXPRESSION
:
4061 // If this is a call statement that doesn't return any
4062 // values, it will not have been counted as a value to
4063 // move. We need to move any subexpressions in case they
4064 // are themselves call statements that require passing a
4066 Expression
* expr
= stmt
->expression_statement()->expr();
4067 if (expr
->call_expression() != NULL
4068 && expr
->call_expression()->result_count() == 0)
4070 return TRAVERSE_CONTINUE
;
4074 // We can leave the expression in place.
4075 return TRAVERSE_CONTINUE
;
4079 bool is_thunk
= stmt
->thunk_statement() != NULL
;
4080 Expression_statement
* es
= stmt
->expression_statement();
4081 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4082 p
!= find_eval_ordering
.end();
4085 Expression
** pexpr
= *p
;
4087 // The last expression in a thunk will be the call passed to go
4088 // or defer, which we must not evaluate early.
4089 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
4092 Location loc
= (*pexpr
)->location();
4094 if ((*pexpr
)->call_expression() == NULL
4095 || (*pexpr
)->call_expression()->result_count() < 2)
4097 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4100 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4104 // A call expression which returns multiple results needs to
4105 // be handled specially. We can't create a temporary
4106 // because there is no type to give it. Any actual uses of
4107 // the values will be done via Call_result_expressions.
4109 // Since a given call expression can be shared by multiple
4110 // Call_result_expressions, avoid hoisting the call the
4111 // second time we see it here. In addition, don't try to
4112 // hoist the top-level multi-return call in the statement,
4113 // since doing this would result a tree with more than one copy
4115 if (this->remember_expression(*pexpr
))
4117 else if (es
!= NULL
&& *pexpr
== es
->expr())
4120 s
= Statement::make_statement(*pexpr
, true);
4125 block
->insert_statement_before(*pindex
, s
);
4130 if (init
!= orig_init
)
4131 vds
->var()->var_value()->set_init(init
);
4133 return TRAVERSE_CONTINUE
;
4136 // Implement the order of evaluation rules for the initializer of a
4140 Order_eval::variable(Named_object
* no
)
4142 if (no
->is_result_variable())
4143 return TRAVERSE_CONTINUE
;
4144 Variable
* var
= no
->var_value();
4145 Expression
* init
= var
->init();
4146 if (!var
->is_global() || init
== NULL
)
4147 return TRAVERSE_CONTINUE
;
4149 Find_eval_ordering find_eval_ordering
;
4150 Expression::traverse(&init
, &find_eval_ordering
);
4152 if (find_eval_ordering
.size() <= 1)
4154 // If there is only one expression with a side-effect, we can
4155 // leave it in place.
4156 return TRAVERSE_SKIP_COMPONENTS
;
4159 Expression
* orig_init
= init
;
4161 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4162 p
!= find_eval_ordering
.end();
4165 Expression
** pexpr
= *p
;
4166 Location loc
= (*pexpr
)->location();
4168 if ((*pexpr
)->call_expression() == NULL
4169 || (*pexpr
)->call_expression()->result_count() < 2)
4171 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4174 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4178 // A call expression which returns multiple results needs to
4179 // be handled specially.
4180 s
= Statement::make_statement(*pexpr
, true);
4182 var
->add_preinit_statement(this->gogo_
, s
);
4185 if (init
!= orig_init
)
4186 var
->set_init(init
);
4188 return TRAVERSE_SKIP_COMPONENTS
;
4191 // Use temporary variables to implement the order of evaluation rules.
4194 Gogo::order_evaluations()
4196 Order_eval
order_eval(this);
4197 this->traverse(&order_eval
);
4200 // Order evaluations in a block.
4203 Gogo::order_block(Block
* block
)
4205 Order_eval
order_eval(this);
4206 block
->traverse(&order_eval
);
4209 // A traversal class used to find a single shortcut operator within an
4212 class Find_shortcut
: public Traverse
4216 : Traverse(traverse_blocks
4217 | traverse_statements
4218 | traverse_expressions
),
4222 // A pointer to the expression which was found, or NULL if none was
4226 { return this->found_
; }
4231 { return TRAVERSE_SKIP_COMPONENTS
; }
4234 statement(Block
*, size_t*, Statement
*)
4235 { return TRAVERSE_SKIP_COMPONENTS
; }
4238 expression(Expression
**);
4241 Expression
** found_
;
4244 // Find a shortcut expression.
4247 Find_shortcut::expression(Expression
** pexpr
)
4249 Expression
* expr
= *pexpr
;
4250 Binary_expression
* be
= expr
->binary_expression();
4252 return TRAVERSE_CONTINUE
;
4253 Operator op
= be
->op();
4254 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
4255 return TRAVERSE_CONTINUE
;
4256 go_assert(this->found_
== NULL
);
4257 this->found_
= pexpr
;
4258 return TRAVERSE_EXIT
;
4261 // A traversal class used to turn shortcut operators into explicit if
4264 class Shortcuts
: public Traverse
4267 Shortcuts(Gogo
* gogo
)
4268 : Traverse(traverse_variables
4269 | traverse_statements
),
4275 variable(Named_object
*);
4278 statement(Block
*, size_t*, Statement
*);
4281 // Convert a shortcut operator.
4283 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
4289 // Remove shortcut operators in a single statement.
4292 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
4294 // FIXME: This approach doesn't work for switch statements, because
4295 // we add the new statements before the whole switch when we need to
4296 // instead add them just before the switch expression. The right
4297 // fix is probably to lower switch statements with nonconstant cases
4298 // to a series of conditionals.
4299 if (s
->switch_statement() != NULL
)
4300 return TRAVERSE_CONTINUE
;
4304 Find_shortcut find_shortcut
;
4306 // If S is a variable declaration, then ordinary traversal won't
4307 // do anything. We want to explicitly traverse the
4308 // initialization expression if there is one.
4309 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
4310 Expression
* init
= NULL
;
4312 s
->traverse_contents(&find_shortcut
);
4315 init
= vds
->var()->var_value()->init();
4317 return TRAVERSE_CONTINUE
;
4318 init
->traverse(&init
, &find_shortcut
);
4320 Expression
** pshortcut
= find_shortcut
.found();
4321 if (pshortcut
== NULL
)
4322 return TRAVERSE_CONTINUE
;
4324 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
4325 block
->insert_statement_before(*pindex
, snew
);
4328 if (pshortcut
== &init
)
4329 vds
->var()->var_value()->set_init(init
);
4333 // Remove shortcut operators in the initializer of a global variable.
4336 Shortcuts::variable(Named_object
* no
)
4338 if (no
->is_result_variable())
4339 return TRAVERSE_CONTINUE
;
4340 Variable
* var
= no
->var_value();
4341 Expression
* init
= var
->init();
4342 if (!var
->is_global() || init
== NULL
)
4343 return TRAVERSE_CONTINUE
;
4347 Find_shortcut find_shortcut
;
4348 init
->traverse(&init
, &find_shortcut
);
4349 Expression
** pshortcut
= find_shortcut
.found();
4350 if (pshortcut
== NULL
)
4351 return TRAVERSE_CONTINUE
;
4353 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
4354 var
->add_preinit_statement(this->gogo_
, snew
);
4355 if (pshortcut
== &init
)
4356 var
->set_init(init
);
4360 // Given an expression which uses a shortcut operator, return a
4361 // statement which implements it, and update *PSHORTCUT accordingly.
4364 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
4366 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
4367 Expression
* left
= shortcut
->left();
4368 Expression
* right
= shortcut
->right();
4369 Location loc
= shortcut
->location();
4371 Block
* retblock
= new Block(enclosing
, loc
);
4372 retblock
->set_end_location(loc
);
4374 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
4376 retblock
->add_statement(ts
);
4378 Block
* block
= new Block(retblock
, loc
);
4379 block
->set_end_location(loc
);
4380 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
4381 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
4382 block
->add_statement(assign
);
4384 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
4385 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
4386 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
4388 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
4390 retblock
->add_statement(if_statement
);
4392 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
4396 // Now convert any shortcut operators in LEFT and RIGHT.
4397 // LEFT and RIGHT were skipped in the top level
4398 // Gogo::order_evaluations. We need to order their
4399 // components first.
4400 Order_eval
order_eval(this->gogo_
);
4401 retblock
->traverse(&order_eval
);
4402 Shortcuts
shortcuts(this->gogo_
);
4403 retblock
->traverse(&shortcuts
);
4405 return Statement::make_block_statement(retblock
, loc
);
4408 // Turn shortcut operators into explicit if statements. Doing this
4409 // considerably simplifies the order of evaluation rules.
4412 Gogo::remove_shortcuts()
4414 Shortcuts
shortcuts(this);
4415 this->traverse(&shortcuts
);
4418 // Turn shortcut operators into explicit if statements in a block.
4421 Gogo::remove_shortcuts_in_block(Block
* block
)
4423 Shortcuts
shortcuts(this);
4424 block
->traverse(&shortcuts
);
4427 // Traversal to flatten parse tree after order of evaluation rules are applied.
4429 class Flatten
: public Traverse
4432 Flatten(Gogo
* gogo
, Named_object
* function
)
4433 : Traverse(traverse_variables
4434 | traverse_functions
4435 | traverse_statements
4436 | traverse_expressions
),
4437 gogo_(gogo
), function_(function
), inserter_()
4441 set_inserter(const Statement_inserter
* inserter
)
4442 { this->inserter_
= *inserter
; }
4445 variable(Named_object
*);
4448 function(Named_object
*);
4451 statement(Block
*, size_t* pindex
, Statement
*);
4454 expression(Expression
**);
4459 // The function we are traversing.
4460 Named_object
* function_
;
4461 // Current statement inserter for use by expressions.
4462 Statement_inserter inserter_
;
4465 // Flatten variables.
4468 Flatten::variable(Named_object
* no
)
4470 if (!no
->is_variable())
4471 return TRAVERSE_CONTINUE
;
4473 if (no
->is_variable() && no
->var_value()->is_global())
4475 // Global variables can have loops in their initialization
4476 // expressions. This is handled in flatten_init_expression.
4477 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
4479 return TRAVERSE_CONTINUE
;
4482 if (!no
->var_value()->is_parameter()
4483 && !no
->var_value()->is_receiver()
4484 && !no
->var_value()->is_closure()
4485 && no
->var_value()->is_non_escaping_address_taken()
4486 && !no
->var_value()->is_in_heap()
4487 && no
->var_value()->toplevel_decl() == NULL
)
4489 // Local variable that has address taken but not escape.
4490 // It needs to be live beyond its lexical scope. So we
4491 // create a top-level declaration for it.
4492 // No need to do it if it is already in the top level.
4493 Block
* top_block
= function_
->func_value()->block();
4494 if (top_block
->bindings()->lookup_local(no
->name()) != no
)
4496 Variable
* var
= no
->var_value();
4497 Temporary_statement
* ts
=
4498 Statement::make_temporary(var
->type(), NULL
, var
->location());
4499 ts
->set_is_address_taken();
4500 top_block
->add_statement_at_front(ts
);
4501 var
->set_toplevel_decl(ts
);
4505 go_assert(!no
->var_value()->has_pre_init());
4507 return TRAVERSE_SKIP_COMPONENTS
;
4510 // Flatten the body of a function. Record the function while flattening it,
4511 // so that we can pass it down when flattening an expression.
4514 Flatten::function(Named_object
* no
)
4516 go_assert(this->function_
== NULL
);
4517 this->function_
= no
;
4518 int t
= no
->func_value()->traverse(this);
4519 this->function_
= NULL
;
4521 if (t
== TRAVERSE_EXIT
)
4523 return TRAVERSE_SKIP_COMPONENTS
;
4526 // Flatten statement parse trees.
4529 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
4531 // Because we explicitly traverse the statement's contents
4532 // ourselves, we want to skip block statements here. There is
4533 // nothing to flatten in a block statement.
4534 if (sorig
->is_block_statement())
4535 return TRAVERSE_CONTINUE
;
4537 Statement_inserter
hold_inserter(this->inserter_
);
4538 this->inserter_
= Statement_inserter(block
, pindex
);
4540 // Flatten the expressions first.
4541 int t
= sorig
->traverse_contents(this);
4542 if (t
== TRAVERSE_EXIT
)
4544 this->inserter_
= hold_inserter
;
4548 // Keep flattening until nothing changes.
4549 Statement
* s
= sorig
;
4552 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
4557 t
= s
->traverse_contents(this);
4558 if (t
== TRAVERSE_EXIT
)
4560 this->inserter_
= hold_inserter
;
4566 block
->replace_statement(*pindex
, s
);
4568 this->inserter_
= hold_inserter
;
4569 return TRAVERSE_SKIP_COMPONENTS
;
4572 // Flatten expression parse trees.
4575 Flatten::expression(Expression
** pexpr
)
4577 // Keep flattening until nothing changes.
4580 Expression
* e
= *pexpr
;
4581 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
4582 return TRAVERSE_EXIT
;
4584 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
4590 return TRAVERSE_SKIP_COMPONENTS
;
4596 Gogo::flatten_block(Named_object
* function
, Block
* block
)
4598 Flatten
flatten(this, function
);
4599 block
->traverse(&flatten
);
4602 // Flatten an expression. INSERTER may be NULL, in which case the
4603 // expression had better not need to create any temporaries.
4606 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
4609 Flatten
flatten(this, function
);
4610 if (inserter
!= NULL
)
4611 flatten
.set_inserter(inserter
);
4612 flatten
.expression(pexpr
);
4618 Flatten
flatten(this, NULL
);
4619 this->traverse(&flatten
);
4622 // Traversal to convert calls to the predeclared recover function to
4623 // pass in an argument indicating whether it can recover from a panic
4626 class Convert_recover
: public Traverse
4629 Convert_recover(Named_object
* arg
)
4630 : Traverse(traverse_expressions
),
4636 expression(Expression
**);
4639 // The argument to pass to the function.
4643 // Convert calls to recover.
4646 Convert_recover::expression(Expression
** pp
)
4648 Call_expression
* ce
= (*pp
)->call_expression();
4649 if (ce
!= NULL
&& ce
->is_recover_call())
4650 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
4652 return TRAVERSE_CONTINUE
;
4655 // Traversal for build_recover_thunks.
4657 class Build_recover_thunks
: public Traverse
4660 Build_recover_thunks(Gogo
* gogo
)
4661 : Traverse(traverse_functions
),
4666 function(Named_object
*);
4670 can_recover_arg(Location
);
4676 // If this function calls recover, turn it into a thunk.
4679 Build_recover_thunks::function(Named_object
* orig_no
)
4681 Function
* orig_func
= orig_no
->func_value();
4682 if (!orig_func
->calls_recover()
4683 || orig_func
->is_recover_thunk()
4684 || orig_func
->has_recover_thunk())
4685 return TRAVERSE_CONTINUE
;
4687 Gogo
* gogo
= this->gogo_
;
4688 Location location
= orig_func
->location();
4693 Function_type
* orig_fntype
= orig_func
->type();
4694 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4695 std::string receiver_name
;
4696 if (orig_fntype
->is_method())
4698 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4699 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4701 receiver_name
= buf
;
4702 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4703 receiver
->location()));
4705 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4706 if (orig_params
!= NULL
&& !orig_params
->empty())
4708 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4709 p
!= orig_params
->end();
4712 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4714 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4718 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4720 std::string can_recover_name
= buf
;
4721 new_params
->push_back(Typed_identifier(can_recover_name
,
4722 Type::lookup_bool_type(),
4723 orig_fntype
->location()));
4725 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4726 Typed_identifier_list
* new_results
;
4727 if (orig_results
== NULL
|| orig_results
->empty())
4731 new_results
= new Typed_identifier_list();
4732 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4733 p
!= orig_results
->end();
4735 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4738 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4740 orig_fntype
->location());
4741 if (orig_fntype
->is_varargs())
4742 new_fntype
->set_is_varargs();
4745 if (orig_fntype
->is_method())
4746 rtype
= orig_fntype
->receiver()->type();
4747 std::string
name(gogo
->recover_thunk_name(orig_no
->name(), rtype
));
4748 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4750 Function
*new_func
= new_no
->func_value();
4751 if (orig_func
->enclosing() != NULL
)
4752 new_func
->set_enclosing(orig_func
->enclosing());
4754 // We build the code for the original function attached to the new
4755 // function, and then swap the original and new function bodies.
4756 // This means that existing references to the original function will
4757 // then refer to the new function. That makes this code a little
4758 // confusing, in that the reference to NEW_NO really refers to the
4759 // other function, not the one we are building.
4761 Expression
* closure
= NULL
;
4762 if (orig_func
->needs_closure())
4764 // For the new function we are creating, declare a new parameter
4765 // variable NEW_CLOSURE_NO and set it to be the closure variable
4766 // of the function. This will be set to the closure value
4767 // passed in by the caller. Then pass a reference to this
4768 // variable as the closure value when calling the original
4769 // function. In other words, simply pass the closure value
4770 // through the thunk we are creating.
4771 Named_object
* orig_closure_no
= orig_func
->closure_var();
4772 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4773 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4774 false, false, location
);
4775 new_var
->set_is_closure();
4776 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4778 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4780 new_func
->set_closure_var(new_closure_no
);
4781 closure
= Expression::make_var_reference(new_closure_no
, location
);
4784 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4786 Expression_list
* args
= new Expression_list();
4787 if (new_params
!= NULL
)
4789 // Note that we skip the last parameter, which is the boolean
4790 // indicating whether recover can succed.
4791 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4792 p
+ 1 != new_params
->end();
4795 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4796 go_assert(p_no
!= NULL
4797 && p_no
->is_variable()
4798 && p_no
->var_value()->is_parameter());
4799 args
->push_back(Expression::make_var_reference(p_no
, location
));
4802 args
->push_back(this->can_recover_arg(location
));
4804 gogo
->start_block(location
);
4806 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4808 // Any varargs call has already been lowered.
4809 call
->set_varargs_are_lowered();
4811 Statement
* s
= Statement::make_return_from_call(call
, location
);
4812 s
->determine_types();
4813 gogo
->add_statement(s
);
4815 Block
* b
= gogo
->finish_block(location
);
4817 gogo
->add_block(b
, location
);
4819 // Lower the call in case it returns multiple results.
4820 gogo
->lower_block(new_no
, b
);
4822 gogo
->finish_function(location
);
4824 // Swap the function bodies and types.
4825 new_func
->swap_for_recover(orig_func
);
4826 orig_func
->set_is_recover_thunk();
4827 new_func
->set_calls_recover();
4828 new_func
->set_has_recover_thunk();
4830 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4831 Bindings
* new_bindings
= new_func
->block()->bindings();
4832 if (orig_fntype
->is_method())
4834 // We changed the receiver to be a regular parameter. We have
4835 // to update the binding accordingly in both functions.
4836 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4837 go_assert(orig_rec_no
!= NULL
4838 && orig_rec_no
->is_variable()
4839 && !orig_rec_no
->var_value()->is_receiver());
4840 orig_rec_no
->var_value()->set_is_receiver();
4842 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4843 if (new_receiver_name
.empty())
4845 // Find the receiver. It was named "r.NNN" in
4846 // Gogo::start_function.
4847 for (Bindings::const_definitions_iterator p
=
4848 new_bindings
->begin_definitions();
4849 p
!= new_bindings
->end_definitions();
4852 const std::string
& pname((*p
)->name());
4853 if (pname
[0] == 'r' && pname
[1] == '.')
4855 new_receiver_name
= pname
;
4859 go_assert(!new_receiver_name
.empty());
4861 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4862 if (new_rec_no
== NULL
)
4863 go_assert(saw_errors());
4866 go_assert(new_rec_no
->is_variable()
4867 && new_rec_no
->var_value()->is_receiver());
4868 new_rec_no
->var_value()->set_is_not_receiver();
4872 // Because we flipped blocks but not types, the can_recover
4873 // parameter appears in the (now) old bindings as a parameter.
4874 // Change it to a local variable, whereupon it will be discarded.
4875 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4876 go_assert(can_recover_no
!= NULL
4877 && can_recover_no
->is_variable()
4878 && can_recover_no
->var_value()->is_parameter());
4879 orig_bindings
->remove_binding(can_recover_no
);
4881 // Add the can_recover argument to the (now) new bindings, and
4882 // attach it to any recover statements.
4883 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4884 false, true, false, location
);
4885 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4887 Convert_recover
convert_recover(can_recover_no
);
4888 new_func
->traverse(&convert_recover
);
4890 // Update the function pointers in any named results.
4891 new_func
->update_result_variables();
4892 orig_func
->update_result_variables();
4894 return TRAVERSE_CONTINUE
;
4897 // Return the expression to pass for the .can_recover parameter to the
4898 // new function. This indicates whether a call to recover may return
4899 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4902 Build_recover_thunks::can_recover_arg(Location location
)
4904 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
4905 static Named_object
* can_recover
;
4906 if (can_recover
== NULL
)
4908 const Location bloc
= Linemap::predeclared_location();
4909 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4910 param_types
->push_back(Typed_identifier("a", uintptr_type
, bloc
));
4911 Type
* boolean_type
= Type::lookup_bool_type();
4912 Typed_identifier_list
* results
= new Typed_identifier_list();
4913 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4914 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4917 Named_object::make_function_declaration("runtime_canrecover",
4918 NULL
, fntype
, bloc
);
4919 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4922 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4923 Expression
* call
= Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS
,
4924 location
, 1, zexpr
);
4925 call
= Expression::make_unsafe_cast(uintptr_type
, call
, location
);
4927 Expression_list
* args
= new Expression_list();
4928 args
->push_back(call
);
4930 Expression
* fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4931 return Expression::make_call(fn
, args
, false, location
);
4934 // Build thunks for functions which call recover. We build a new
4935 // function with an extra parameter, which is whether a call to
4936 // recover can succeed. We then move the body of this function to
4937 // that one. We then turn this function into a thunk which calls the
4938 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4939 // The function will be marked as not splitting the stack. This will
4940 // cooperate with the implementation of defer to make recover do the
4944 Gogo::build_recover_thunks()
4946 Build_recover_thunks
build_recover_thunks(this);
4947 this->traverse(&build_recover_thunks
);
4950 // Look for named types to see whether we need to create an interface
4953 class Build_method_tables
: public Traverse
4956 Build_method_tables(Gogo
* gogo
,
4957 const std::vector
<Interface_type
*>& interfaces
)
4958 : Traverse(traverse_types
),
4959 gogo_(gogo
), interfaces_(interfaces
)
4968 // A list of locally defined interfaces which have hidden methods.
4969 const std::vector
<Interface_type
*>& interfaces_
;
4972 // Build all required interface method tables for types. We need to
4973 // ensure that we have an interface method table for every interface
4974 // which has a hidden method, for every named type which implements
4975 // that interface. Normally we can just build interface method tables
4976 // as we need them. However, in some cases we can require an
4977 // interface method table for an interface defined in a different
4978 // package for a type defined in that package. If that interface and
4979 // type both use a hidden method, that is OK. However, we will not be
4980 // able to build that interface method table when we need it, because
4981 // the type's hidden method will be static. So we have to build it
4982 // here, and just refer it from other packages as needed.
4985 Gogo::build_interface_method_tables()
4990 std::vector
<Interface_type
*> hidden_interfaces
;
4991 hidden_interfaces
.reserve(this->interface_types_
.size());
4992 for (std::vector
<Interface_type
*>::const_iterator pi
=
4993 this->interface_types_
.begin();
4994 pi
!= this->interface_types_
.end();
4997 const Typed_identifier_list
* methods
= (*pi
)->methods();
4998 if (methods
== NULL
)
5000 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
5001 pm
!= methods
->end();
5004 if (Gogo::is_hidden_name(pm
->name()))
5006 hidden_interfaces
.push_back(*pi
);
5012 if (!hidden_interfaces
.empty())
5014 // Now traverse the tree looking for all named types.
5015 Build_method_tables
bmt(this, hidden_interfaces
);
5016 this->traverse(&bmt
);
5019 // We no longer need the list of interfaces.
5021 this->interface_types_
.clear();
5024 // This is called for each type. For a named type, for each of the
5025 // interfaces with hidden methods that it implements, create the
5029 Build_method_tables::type(Type
* type
)
5031 Named_type
* nt
= type
->named_type();
5032 Struct_type
* st
= type
->struct_type();
5033 if (nt
!= NULL
|| st
!= NULL
)
5035 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
5036 for (std::vector
<Interface_type
*>::const_iterator p
=
5037 this->interfaces_
.begin();
5038 p
!= this->interfaces_
.end();
5041 // We ask whether a pointer to the named type implements the
5042 // interface, because a pointer can implement more methods
5046 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
5049 nt
->interface_method_table(*p
, false)->get_backend(&context
);
5050 nt
->interface_method_table(*p
, true)->get_backend(&context
);
5055 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
5058 st
->interface_method_table(*p
, false)->get_backend(&context
);
5059 st
->interface_method_table(*p
, true)->get_backend(&context
);
5064 return TRAVERSE_CONTINUE
;
5067 // Return an expression which allocates memory to hold values of type TYPE.
5070 Gogo::allocate_memory(Type
* type
, Location location
)
5072 Expression
* td
= Expression::make_type_descriptor(type
, location
);
5073 return Runtime::make_call(Runtime::NEW
, location
, 1, td
);
5076 // Traversal class used to check for return statements.
5078 class Check_return_statements_traverse
: public Traverse
5081 Check_return_statements_traverse()
5082 : Traverse(traverse_functions
)
5086 function(Named_object
*);
5089 // Check that a function has a return statement if it needs one.
5092 Check_return_statements_traverse::function(Named_object
* no
)
5094 Function
* func
= no
->func_value();
5095 const Function_type
* fntype
= func
->type();
5096 const Typed_identifier_list
* results
= fntype
->results();
5098 // We only need a return statement if there is a return value.
5099 if (results
== NULL
|| results
->empty())
5100 return TRAVERSE_CONTINUE
;
5102 if (func
->block()->may_fall_through())
5103 go_error_at(func
->block()->end_location(),
5104 "missing return at end of function");
5106 return TRAVERSE_CONTINUE
;
5109 // Check return statements.
5112 Gogo::check_return_statements()
5114 Check_return_statements_traverse traverse
;
5115 this->traverse(&traverse
);
5118 // Traversal class to decide whether a function body is less than the
5119 // inlining budget. This adjusts *available as it goes, and stops the
5120 // traversal if it goes negative.
5122 class Inline_within_budget
: public Traverse
5125 Inline_within_budget(int* available
)
5126 : Traverse(traverse_statements
5127 | traverse_expressions
),
5128 available_(available
)
5132 statement(Block
*, size_t*, Statement
*);
5135 expression(Expression
**);
5138 // Pointer to remaining budget.
5142 // Adjust the budget for the inlining cost of a statement.
5145 Inline_within_budget::statement(Block
*, size_t*, Statement
* s
)
5147 if (*this->available_
< 0)
5148 return TRAVERSE_EXIT
;
5149 *this->available_
-= s
->inlining_cost();
5150 return TRAVERSE_CONTINUE
;
5153 // Adjust the budget for the inlining cost of an expression.
5156 Inline_within_budget::expression(Expression
** pexpr
)
5158 if (*this->available_
< 0)
5159 return TRAVERSE_EXIT
;
5160 *this->available_
-= (*pexpr
)->inlining_cost();
5161 return TRAVERSE_CONTINUE
;
5164 // Traversal class to find functions whose body should be exported for
5165 // inlining by other packages.
5167 class Mark_inline_candidates
: public Traverse
5170 Mark_inline_candidates(Unordered_set(Named_object
*)* marked
)
5171 : Traverse(traverse_functions
5173 marked_functions_(marked
)
5177 function(Named_object
*);
5183 // We traverse the function body trying to determine how expensive
5184 // it is for inlining. We start with a budget, and decrease that
5185 // budget for each statement and expression. If the budget goes
5186 // negative, we do not export the function body. The value of this
5187 // budget is a heuristic. In the usual GCC spirit, we could
5188 // consider setting this via a command line option.
5189 const int budget_heuristic
= 80;
5191 // Set of named objects that are marked as inline candidates.
5192 Unordered_set(Named_object
*)* marked_functions_
;
5195 // Mark a function if it is an inline candidate.
5198 Mark_inline_candidates::function(Named_object
* no
)
5200 Function
* func
= no
->func_value();
5201 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5202 return TRAVERSE_CONTINUE
;
5203 int budget
= budget_heuristic
;
5204 Inline_within_budget
iwb(&budget
);
5205 func
->block()->traverse(&iwb
);
5208 func
->set_export_for_inlining();
5209 this->marked_functions_
->insert(no
);
5211 return TRAVERSE_CONTINUE
;
5214 // Mark methods if they are inline candidates.
5217 Mark_inline_candidates::type(Type
* t
)
5219 Named_type
* nt
= t
->named_type();
5220 if (nt
== NULL
|| nt
->is_alias())
5221 return TRAVERSE_CONTINUE
;
5222 const Bindings
* methods
= nt
->local_methods();
5223 if (methods
== NULL
)
5224 return TRAVERSE_CONTINUE
;
5225 for (Bindings::const_definitions_iterator p
= methods
->begin_definitions();
5226 p
!= methods
->end_definitions();
5229 Named_object
* no
= *p
;
5230 go_assert(no
->is_function());
5231 Function
*func
= no
->func_value();
5232 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5234 int budget
= budget_heuristic
;
5235 Inline_within_budget
iwb(&budget
);
5236 func
->block()->traverse(&iwb
);
5239 func
->set_export_for_inlining();
5240 this->marked_functions_
->insert(no
);
5243 return TRAVERSE_CONTINUE
;
5246 // Export identifiers as requested.
5254 // Mark any functions whose body should be exported for inlining by
5256 Unordered_set(Named_object
*) marked_functions
;
5257 Mark_inline_candidates
mic(&marked_functions
);
5258 this->traverse(&mic
);
5260 // For now we always stream to a section. Later we may want to
5261 // support streaming to a separate file.
5262 Stream_to_section
stream(this->backend());
5264 // Write out either the prefix or pkgpath depending on how we were
5267 std::string pkgpath
;
5268 if (this->pkgpath_from_option_
)
5269 pkgpath
= this->pkgpath_
;
5270 else if (this->prefix_from_option_
)
5271 prefix
= this->prefix_
;
5272 else if (this->is_main_package())
5277 std::string init_fn_name
;
5278 if (this->is_main_package())
5280 else if (this->need_init_fn_
)
5281 init_fn_name
= this->get_init_fn_name();
5283 init_fn_name
= this->dummy_init_fn_name();
5285 Export
exp(&stream
);
5286 exp
.register_builtin_types(this);
5287 exp
.export_globals(this->package_name(),
5293 this->imported_init_fns_
,
5294 this->package_
->bindings(),
5297 if (!this->c_header_
.empty() && !saw_errors())
5298 this->write_c_header();
5301 // Write the top level named struct types in C format to a C header
5302 // file. This is used when building the runtime package, to share
5303 // struct definitions between C and Go.
5306 Gogo::write_c_header()
5309 out
.open(this->c_header_
.c_str());
5312 go_error_at(Linemap::unknown_location(),
5313 "cannot open %s: %m", this->c_header_
.c_str());
5317 std::list
<Named_object
*> types
;
5318 Bindings
* top
= this->package_
->bindings();
5319 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
5320 p
!= top
->end_definitions();
5323 Named_object
* no
= *p
;
5325 // Skip names that start with underscore followed by something
5326 // other than an uppercase letter, as when compiling the runtime
5327 // package they are mostly types defined by mkrsysinfo.sh based
5328 // on the C system header files. We don't need to translate
5329 // types to C and back to Go. But do accept the special cases
5330 // _defer, _panic, and _type.
5331 std::string name
= Gogo::unpack_hidden_name(no
->name());
5333 && (name
[1] < 'A' || name
[1] > 'Z')
5334 && (name
!= "_defer" && name
!= "_panic" && name
!= "_type"))
5337 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
5338 types
.push_back(no
);
5340 && no
->const_value()->type()->integer_type() != NULL
5341 && !no
->const_value()->is_sink())
5343 Numeric_constant nc
;
5345 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
5346 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
5348 out
<< "#define " << no
->message_name() << ' ' << val
5354 std::vector
<const Named_object
*> written
;
5356 while (!types
.empty())
5358 Named_object
* no
= types
.front();
5361 std::vector
<const Named_object
*> needs
;
5362 std::vector
<const Named_object
*> declare
;
5363 if (!no
->type_value()->struct_type()->can_write_to_c_header(&needs
,
5368 for (std::vector
<const Named_object
*>::const_iterator pr
5370 pr
!= needs
.end() && ok
;
5373 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
5374 pt
!= types
.end() && ok
;
5384 // This should be impossible since the code parsed and
5389 types
.push_back(no
);
5393 for (std::vector
<const Named_object
*>::const_iterator pd
5395 pd
!= declare
.end();
5401 std::vector
<const Named_object
*> dneeds
;
5402 std::vector
<const Named_object
*> ddeclare
;
5403 if (!(*pd
)->type_value()->struct_type()->
5404 can_write_to_c_header(&dneeds
, &ddeclare
))
5408 for (std::vector
<const Named_object
*>::const_iterator pw
5410 pw
!= written
.end();
5422 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
5423 written
.push_back(*pd
);
5428 out
<< "struct " << no
->message_name() << " {" << std::endl
;
5429 no
->type_value()->struct_type()->write_to_c_header(out
);
5430 out
<< "};" << std::endl
;
5431 written
.push_back(no
);
5436 go_error_at(Linemap::unknown_location(),
5437 "error writing to %s: %m", this->c_header_
.c_str());
5440 // Find the blocks in order to convert named types defined in blocks.
5442 class Convert_named_types
: public Traverse
5445 Convert_named_types(Gogo
* gogo
)
5446 : Traverse(traverse_blocks
),
5452 block(Block
* block
);
5459 Convert_named_types::block(Block
* block
)
5461 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
5462 return TRAVERSE_CONTINUE
;
5465 // Convert all named types to the backend representation. Since named
5466 // types can refer to other types, this needs to be done in the right
5467 // sequence, which is handled by Named_type::convert. Here we arrange
5468 // to call that for each named type.
5471 Gogo::convert_named_types()
5473 this->convert_named_types_in_bindings(this->globals_
);
5474 for (Packages::iterator p
= this->packages_
.begin();
5475 p
!= this->packages_
.end();
5478 Package
* package
= p
->second
;
5479 this->convert_named_types_in_bindings(package
->bindings());
5482 Convert_named_types
cnt(this);
5483 this->traverse(&cnt
);
5485 // Make all the builtin named types used for type descriptors, and
5486 // then convert them. They will only be written out if they are
5488 Type::make_type_descriptor_type();
5489 Type::make_type_descriptor_ptr_type();
5490 Function_type::make_function_type_descriptor_type();
5491 Pointer_type::make_pointer_type_descriptor_type();
5492 Struct_type::make_struct_type_descriptor_type();
5493 Array_type::make_array_type_descriptor_type();
5494 Array_type::make_slice_type_descriptor_type();
5495 Map_type::make_map_type_descriptor_type();
5496 Channel_type::make_chan_type_descriptor_type();
5497 Interface_type::make_interface_type_descriptor_type();
5498 Expression::make_func_descriptor_type();
5499 Type::convert_builtin_named_types(this);
5501 Runtime::convert_types(this);
5503 this->named_types_are_converted_
= true;
5505 Type::finish_pointer_types(this);
5508 // Convert all names types in a set of bindings.
5511 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
5513 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
5514 p
!= bindings
->end_definitions();
5517 if ((*p
)->is_type())
5518 (*p
)->type_value()->convert(this);
5523 debug_go_gogo(Gogo
* gogo
)
5532 std::cerr
<< "Packages:\n";
5533 for (Packages::const_iterator p
= this->packages_
.begin();
5534 p
!= this->packages_
.end();
5537 const char *tag
= " ";
5538 if (p
->second
== this->package_
)
5540 std::cerr
<< tag
<< "'" << p
->first
<< "' "
5541 << p
->second
->pkgpath() << " " << ((void*)p
->second
) << "\n";
5547 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
5549 : type_(type
), enclosing_(enclosing
), results_(NULL
),
5550 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
5551 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
5552 pragmas_(0), nested_functions_(0), is_sink_(false),
5553 results_are_named_(false), is_unnamed_type_stub_method_(false),
5554 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5555 calls_defer_retaddr_(false), is_type_specific_function_(false),
5556 in_unique_section_(false), export_for_inlining_(false),
5557 is_inline_only_(false), is_referenced_by_inline_(false),
5558 is_exported_by_linkname_(false)
5562 // Create the named result variables.
5565 Function::create_result_variables(Gogo
* gogo
)
5567 const Typed_identifier_list
* results
= this->type_
->results();
5568 if (results
== NULL
|| results
->empty())
5571 if (!results
->front().name().empty())
5572 this->results_are_named_
= true;
5574 this->results_
= new Results();
5575 this->results_
->reserve(results
->size());
5577 Block
* block
= this->block_
;
5579 for (Typed_identifier_list::const_iterator p
= results
->begin();
5580 p
!= results
->end();
5583 std::string name
= p
->name();
5584 if (name
.empty() || Gogo::is_sink_name(name
))
5586 static int result_counter
;
5588 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
5590 name
= gogo
->pack_hidden_name(buf
, false);
5592 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
5594 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
5595 if (no
->is_result_variable())
5596 this->results_
->push_back(no
);
5599 static int dummy_result_count
;
5601 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
5602 ++dummy_result_count
;
5603 name
= gogo
->pack_hidden_name(buf
, false);
5604 no
= block
->bindings()->add_result_variable(name
, result
);
5605 go_assert(no
->is_result_variable());
5606 this->results_
->push_back(no
);
5611 // Update the named result variables when cloning a function which
5615 Function::update_result_variables()
5617 if (this->results_
== NULL
)
5620 for (Results::iterator p
= this->results_
->begin();
5621 p
!= this->results_
->end();
5623 (*p
)->result_var_value()->set_function(this);
5626 // Whether this method should not be included in the type descriptor.
5629 Function::nointerface() const
5631 go_assert(this->is_method());
5632 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
5635 // Record that this method should not be included in the type
5639 Function::set_nointerface()
5641 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
5644 // Return the closure variable, creating it if necessary.
5647 Function::closure_var()
5649 if (this->closure_var_
== NULL
)
5651 go_assert(this->descriptor_
== NULL
);
5652 // We don't know the type of the variable yet. We add fields as
5654 Location loc
= this->type_
->location();
5655 Struct_field_list
* sfl
= new Struct_field_list
;
5656 Struct_type
* struct_type
= Type::make_struct_type(sfl
, loc
);
5657 struct_type
->set_is_struct_incomparable();
5658 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
5659 NULL
, false, false, false, loc
);
5661 var
->set_is_closure();
5662 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
5663 // Note that the new variable is not in any binding contour.
5665 return this->closure_var_
;
5668 // Set the type of the closure variable.
5671 Function::set_closure_type()
5673 if (this->closure_var_
== NULL
)
5675 Named_object
* closure
= this->closure_var_
;
5676 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
5678 // The first field of a closure is always a pointer to the function
5680 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
5681 st
->push_field(Struct_field(Typed_identifier(".f", voidptr_type
,
5684 unsigned int index
= 1;
5685 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
5686 p
!= this->closure_fields_
.end();
5689 Named_object
* no
= p
->first
;
5691 snprintf(buf
, sizeof buf
, "%u", index
);
5692 std::string n
= no
->name() + buf
;
5694 if (no
->is_variable())
5695 var_type
= no
->var_value()->type();
5697 var_type
= no
->result_var_value()->type();
5698 Type
* field_type
= Type::make_pointer_type(var_type
);
5699 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
5703 // Return whether this function is a method.
5706 Function::is_method() const
5708 return this->type_
->is_method();
5711 // Add a label definition.
5714 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
5717 Label
* lnull
= NULL
;
5718 std::pair
<Labels::iterator
, bool> ins
=
5719 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5721 if (label_name
== "_")
5723 label
= Label::create_dummy_label();
5725 ins
.first
->second
= label
;
5727 else if (ins
.second
)
5729 // This is a new label.
5730 label
= new Label(label_name
);
5731 ins
.first
->second
= label
;
5735 // The label was already in the hash table.
5736 label
= ins
.first
->second
;
5737 if (label
->is_defined())
5739 go_error_at(location
, "label %qs already defined",
5740 Gogo::message_name(label_name
).c_str());
5741 go_inform(label
->location(), "previous definition of %qs was here",
5742 Gogo::message_name(label_name
).c_str());
5743 return new Label(label_name
);
5747 label
->define(location
, gogo
->bindings_snapshot(location
));
5749 // Issue any errors appropriate for any previous goto's to this
5751 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
5752 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
5755 (*p
)->check_goto_to(gogo
->current_block());
5756 label
->clear_refs();
5761 // Add a reference to a label.
5764 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
5765 Location location
, bool issue_goto_errors
)
5767 Label
* lnull
= NULL
;
5768 std::pair
<Labels::iterator
, bool> ins
=
5769 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5773 // The label was already in the hash table.
5774 label
= ins
.first
->second
;
5778 go_assert(ins
.first
->second
== NULL
);
5779 label
= new Label(label_name
);
5780 ins
.first
->second
= label
;
5783 label
->set_is_used();
5785 if (issue_goto_errors
)
5787 Bindings_snapshot
* snapshot
= label
->snapshot();
5788 if (snapshot
!= NULL
)
5789 snapshot
->check_goto_from(gogo
->current_block(), location
);
5791 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
5797 // Warn about labels that are defined but not used.
5800 Function::check_labels() const
5802 for (Labels::const_iterator p
= this->labels_
.begin();
5803 p
!= this->labels_
.end();
5806 Label
* label
= p
->second
;
5807 if (!label
->is_used())
5808 go_error_at(label
->location(), "label %qs defined and not used",
5809 Gogo::message_name(label
->name()).c_str());
5813 // Set the receiver type. This is used to remove aliases.
5816 Function::set_receiver_type(Type
* rtype
)
5818 Function_type
* oft
= this->type_
;
5819 Typed_identifier
* rec
= new Typed_identifier(oft
->receiver()->name(),
5821 oft
->receiver()->location());
5822 Typed_identifier_list
* parameters
= NULL
;
5823 if (oft
->parameters() != NULL
)
5824 parameters
= oft
->parameters()->copy();
5825 Typed_identifier_list
* results
= NULL
;
5826 if (oft
->results() != NULL
)
5827 results
= oft
->results()->copy();
5828 Function_type
* nft
= Type::make_function_type(rec
, parameters
, results
,
5833 // Swap one function with another. This is used when building the
5834 // thunk we use to call a function which calls recover. It may not
5835 // work for any other case.
5838 Function::swap_for_recover(Function
*x
)
5840 go_assert(this->enclosing_
== x
->enclosing_
);
5841 std::swap(this->results_
, x
->results_
);
5842 std::swap(this->closure_var_
, x
->closure_var_
);
5843 std::swap(this->block_
, x
->block_
);
5844 go_assert(this->location_
== x
->location_
);
5845 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
5846 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
5849 // Traverse the tree.
5852 Function::traverse(Traverse
* traverse
)
5854 unsigned int traverse_mask
= traverse
->traverse_mask();
5857 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
5860 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
5861 return TRAVERSE_EXIT
;
5864 // FIXME: We should check traverse_functions here if nested
5865 // functions are stored in block bindings.
5866 if (this->block_
!= NULL
5868 & (Traverse::traverse_variables
5869 | Traverse::traverse_constants
5870 | Traverse::traverse_blocks
5871 | Traverse::traverse_statements
5872 | Traverse::traverse_expressions
5873 | Traverse::traverse_types
)) != 0)
5875 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5876 return TRAVERSE_EXIT
;
5879 return TRAVERSE_CONTINUE
;
5882 // Work out types for unspecified variables and constants.
5885 Function::determine_types()
5887 if (this->block_
!= NULL
)
5888 this->block_
->determine_types();
5891 // Return the function descriptor, the value you get when you refer to
5892 // the function in Go code without calling it.
5895 Function::descriptor(Gogo
*, Named_object
* no
)
5897 go_assert(!this->is_method());
5898 go_assert(this->closure_var_
== NULL
);
5899 if (this->descriptor_
== NULL
)
5900 this->descriptor_
= Expression::make_func_descriptor(no
);
5901 return this->descriptor_
;
5904 // Get a pointer to the variable representing the defer stack for this
5905 // function, making it if necessary. The value of the variable is set
5906 // by the runtime routines to true if the function is returning,
5907 // rather than panicing through. A pointer to this variable is used
5908 // as a marker for the functions on the defer stack associated with
5909 // this function. A function-specific variable permits inlining a
5910 // function which uses defer.
5913 Function::defer_stack(Location location
)
5915 if (this->defer_stack_
== NULL
)
5917 Type
* t
= Type::lookup_bool_type();
5918 Expression
* n
= Expression::make_boolean(false, location
);
5919 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5920 this->defer_stack_
->set_is_address_taken();
5922 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5924 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5927 // Export the function.
5930 Function::export_func(Export
* exp
, const Named_object
* no
) const
5932 Block
* block
= NULL
;
5933 if (this->export_for_inlining())
5934 block
= this->block_
;
5935 Function::export_func_with_type(exp
, no
, this->type_
, this->results_
,
5936 this->is_method() && this->nointerface(),
5937 this->asm_name(), block
, this->location_
);
5940 // Export a function with a type.
5943 Function::export_func_with_type(Export
* exp
, const Named_object
* no
,
5944 const Function_type
* fntype
,
5945 Function::Results
* result_vars
,
5946 bool nointerface
, const std::string
& asm_name
,
5947 Block
* block
, Location loc
)
5949 exp
->write_c_string("func ");
5953 go_assert(fntype
->is_method());
5954 exp
->write_c_string("/*nointerface*/ ");
5957 if (!asm_name
.empty())
5959 exp
->write_c_string("/*asm ");
5960 exp
->write_string(asm_name
);
5961 exp
->write_c_string(" */ ");
5964 if (fntype
->is_method())
5966 exp
->write_c_string("(");
5967 const Typed_identifier
* receiver
= fntype
->receiver();
5968 exp
->write_name(receiver
->name());
5969 exp
->write_escape(receiver
->note());
5970 exp
->write_c_string(" ");
5971 exp
->write_type(receiver
->type()->unalias());
5972 exp
->write_c_string(") ");
5975 if (no
->package() != NULL
&& !fntype
->is_method())
5978 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
5979 exp
->write_c_string(buf
);
5982 const std::string
& name(no
->name());
5983 if (!Gogo::is_hidden_name(name
))
5984 exp
->write_string(name
);
5987 exp
->write_c_string(".");
5988 exp
->write_string(Gogo::unpack_hidden_name(name
));
5991 exp
->write_c_string(" (");
5992 const Typed_identifier_list
* parameters
= fntype
->parameters();
5993 if (parameters
!= NULL
)
5996 bool is_varargs
= fntype
->is_varargs();
5998 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5999 p
!= parameters
->end();
6005 exp
->write_c_string(", ");
6006 exp
->write_name(p
->name());
6007 exp
->write_escape(p
->note());
6008 exp
->write_c_string(" ");
6009 if (!is_varargs
|| p
+ 1 != parameters
->end())
6010 exp
->write_type(p
->type());
6013 exp
->write_c_string("...");
6014 exp
->write_type(p
->type()->array_type()->element_type());
6018 exp
->write_c_string(")");
6020 const Typed_identifier_list
* result_decls
= fntype
->results();
6021 if (result_decls
!= NULL
)
6023 if (result_decls
->size() == 1
6024 && result_decls
->begin()->name().empty()
6027 exp
->write_c_string(" ");
6028 exp
->write_type(result_decls
->begin()->type());
6032 exp
->write_c_string(" (");
6034 Results::const_iterator pr
;
6035 if (result_vars
!= NULL
)
6036 pr
= result_vars
->begin();
6037 for (Typed_identifier_list::const_iterator pd
= result_decls
->begin();
6038 pd
!= result_decls
->end();
6044 exp
->write_c_string(", ");
6045 // We only use pr->name, which may be artificial, if
6046 // need it for inlining.
6047 if (block
== NULL
|| result_vars
== NULL
)
6048 exp
->write_name(pd
->name());
6050 exp
->write_name((*pr
)->name());
6051 exp
->write_escape(pd
->note());
6052 exp
->write_c_string(" ");
6053 exp
->write_type(pd
->type());
6054 if (result_vars
!= NULL
)
6057 if (result_vars
!= NULL
)
6058 go_assert(pr
== result_vars
->end());
6059 exp
->write_c_string(")");
6064 exp
->write_c_string("\n");
6068 if (fntype
->is_method())
6071 Export_function_body
efb(exp
, indent
);
6074 efb
.write_c_string("// ");
6075 efb
.write_string(Linemap::location_to_file(block
->start_location()));
6076 efb
.write_char(':');
6078 snprintf(buf
, sizeof buf
, "%d", Linemap::location_to_line(loc
));
6079 efb
.write_c_string(buf
);
6080 efb
.write_char('\n');
6081 block
->export_block(&efb
);
6083 const std::string
& body(efb
.body());
6085 snprintf(buf
, sizeof buf
, " <inl:%lu>\n",
6086 static_cast<unsigned long>(body
.length()));
6087 exp
->write_c_string(buf
);
6089 exp
->write_string(body
);
6093 // Import a function.
6096 Function::import_func(Import
* imp
, std::string
* pname
,
6097 Package
** ppkg
, bool* pis_exported
,
6098 Typed_identifier
** preceiver
,
6099 Typed_identifier_list
** pparameters
,
6100 Typed_identifier_list
** presults
,
6103 std::string
* asm_name
,
6106 imp
->require_c_string("func ");
6108 *nointerface
= false;
6109 while (imp
->match_c_string("/*"))
6112 if (imp
->match_c_string("nointerface"))
6114 imp
->require_c_string("nointerface*/ ");
6115 *nointerface
= true;
6117 else if (imp
->match_c_string("asm"))
6119 imp
->require_c_string("asm ");
6120 *asm_name
= imp
->read_identifier();
6121 imp
->require_c_string(" */ ");
6125 go_error_at(imp
->location(),
6126 "import error at %d: unrecognized function comment",
6134 // Only a method can be nointerface.
6135 go_assert(imp
->peek_char() == '(');
6139 if (imp
->peek_char() == '(')
6141 imp
->require_c_string("(");
6142 std::string name
= imp
->read_name();
6143 std::string escape_note
= imp
->read_escape();
6144 imp
->require_c_string(" ");
6145 Type
* rtype
= imp
->read_type();
6146 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
6147 (*preceiver
)->set_note(escape_note
);
6148 imp
->require_c_string(") ");
6151 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
6153 go_error_at(imp
->location(),
6154 "import error at %d: bad function name in export data",
6159 Typed_identifier_list
* parameters
;
6160 *is_varargs
= false;
6161 imp
->require_c_string(" (");
6162 if (imp
->peek_char() == ')')
6166 parameters
= new Typed_identifier_list();
6169 std::string name
= imp
->read_name();
6170 std::string escape_note
= imp
->read_escape();
6171 imp
->require_c_string(" ");
6173 if (imp
->match_c_string("..."))
6179 Type
* ptype
= imp
->read_type();
6181 ptype
= Type::make_array_type(ptype
, NULL
);
6182 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
6183 t
.set_note(escape_note
);
6184 parameters
->push_back(t
);
6185 if (imp
->peek_char() != ',')
6187 go_assert(!*is_varargs
);
6188 imp
->require_c_string(", ");
6191 imp
->require_c_string(")");
6192 *pparameters
= parameters
;
6194 Typed_identifier_list
* results
;
6195 if (imp
->peek_char() != ' ' || imp
->match_c_string(" <inl"))
6199 results
= new Typed_identifier_list();
6200 imp
->require_c_string(" ");
6201 if (imp
->peek_char() != '(')
6203 Type
* rtype
= imp
->read_type();
6204 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
6208 imp
->require_c_string("(");
6211 std::string name
= imp
->read_name();
6212 std::string note
= imp
->read_escape();
6213 imp
->require_c_string(" ");
6214 Type
* rtype
= imp
->read_type();
6215 Typed_identifier t
= Typed_identifier(name
, rtype
,
6218 results
->push_back(t
);
6219 if (imp
->peek_char() != ',')
6221 imp
->require_c_string(", ");
6223 imp
->require_c_string(")");
6226 *presults
= results
;
6228 if (!imp
->match_c_string(" <inl:"))
6230 imp
->require_semicolon_if_old_version();
6231 imp
->require_c_string("\n");
6236 imp
->require_c_string(" <inl:");
6241 c
= imp
->peek_char();
6242 if (c
< '0' || c
> '9')
6247 imp
->require_c_string(">\n");
6251 long llen
= strtol(lenstr
.c_str(), &end
, 10);
6254 || (llen
== LONG_MAX
&& errno
== ERANGE
))
6256 go_error_at(imp
->location(), "invalid inline function length %s",
6261 imp
->read(static_cast<size_t>(llen
), body
);
6267 // Get the backend name.
6270 Function::backend_name(Gogo
* gogo
, Named_object
* no
, Backend_name
*bname
)
6272 if (!this->asm_name_
.empty())
6273 bname
->set_asm_name(this->asm_name_
);
6274 else if (no
->package() == NULL
&& no
->name() == gogo
->get_init_fn_name())
6276 // These names appear in the export data and are used
6277 // directly in the assembler code. If we change this here
6278 // we need to change Gogo::init_imports.
6279 bname
->set_asm_name(no
->name());
6281 else if (this->enclosing_
!= NULL
)
6283 // Rewrite the nested name to use the enclosing function name.
6284 // We don't do this earlier because we just store simple names
6285 // in a Named_object, not Backend_names.
6287 // The name was set by nested_function_name, which always
6288 // appends ..funcNNN. We want that to be our suffix.
6289 size_t pos
= no
->name().find("..func");
6290 go_assert(pos
!= std::string::npos
);
6292 Named_object
* enclosing
= this->enclosing_
;
6295 Named_object
* parent
= enclosing
->func_value()->enclosing();
6302 if (enclosing
->func_value()->type()->is_method())
6303 rtype
= enclosing
->func_value()->type()->receiver()->type();
6304 gogo
->function_backend_name(enclosing
->name(), enclosing
->package(),
6306 bname
->append_suffix(no
->name().substr(pos
));
6311 if (this->type_
->is_method())
6312 rtype
= this->type_
->receiver()->type();
6313 gogo
->function_backend_name(no
->name(), no
->package(), rtype
, bname
);
6317 // Get the backend representation.
6320 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6322 if (this->fndecl_
== NULL
)
6324 unsigned int flags
= 0;
6325 if (no
->package() != NULL
)
6327 // Functions defined in other packages must be visible.
6328 flags
|= Backend::function_is_visible
;
6330 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
6332 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
6333 && !this->type_
->is_method())
6335 else if (no
->name() == gogo
->get_init_fn_name())
6336 flags
|= Backend::function_is_visible
;
6337 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
6338 && gogo
->is_main_package())
6339 flags
|= Backend::function_is_visible
;
6340 // Methods have to be public even if they are hidden because
6341 // they can be pulled into type descriptors when using
6342 // anonymous fields.
6343 else if (!Gogo::is_hidden_name(no
->name())
6344 || this->type_
->is_method())
6346 if (!this->is_unnamed_type_stub_method_
)
6347 flags
|= Backend::function_is_visible
;
6350 if (!this->asm_name_
.empty())
6352 // If an assembler name is explicitly specified, there must
6353 // be some reason to refer to the symbol from a different
6355 flags
|= Backend::function_is_visible
;
6358 // If an inline body refers to this function, then it
6359 // needs to be visible in the symbol table.
6360 if (this->is_referenced_by_inline_
)
6361 flags
|= Backend::function_is_visible
;
6363 // A go:linkname directive can be used to force a function to be
6365 if (this->is_exported_by_linkname_
)
6366 flags
|= Backend::function_is_visible
;
6368 // If a function calls the predeclared recover function, we
6369 // can't inline it, because recover behaves differently in a
6370 // function passed directly to defer. If this is a recover
6371 // thunk that we built to test whether a function can be
6372 // recovered, we can't inline it, because that will mess up
6373 // our return address comparison.
6374 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
6376 // If a function calls __go_set_defer_retaddr, then mark it as
6377 // uninlinable. This prevents the GCC backend from splitting
6378 // the function; splitting the function is a bad idea because we
6379 // want the return address label to be in the same function as
6381 if (this->calls_defer_retaddr_
)
6382 is_inlinable
= false;
6384 // Check the //go:noinline compiler directive.
6385 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
6386 is_inlinable
= false;
6389 flags
|= Backend::function_is_inlinable
;
6391 // If this is a thunk created to call a function which calls
6392 // the predeclared recover function, we need to disable
6393 // stack splitting for the thunk.
6394 bool disable_split_stack
= this->is_recover_thunk_
;
6396 // Check the //go:nosplit compiler directive.
6397 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
6398 disable_split_stack
= true;
6400 if (disable_split_stack
)
6401 flags
|= Backend::function_no_split_stack
;
6403 // This should go into a unique section if that has been
6404 // requested elsewhere, or if this is a nointerface function.
6405 // We want to put a nointerface function into a unique section
6406 // because there is a good chance that the linker garbage
6407 // collection can discard it.
6408 if (this->in_unique_section_
6409 || (this->is_method() && this->nointerface()))
6410 flags
|= Backend::function_in_unique_section
;
6412 if (this->is_inline_only_
)
6413 flags
|= Backend::function_only_inline
;
6415 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
6418 this->backend_name(gogo
, no
, &bname
);
6420 this->fndecl_
= gogo
->backend()->function(functype
,
6422 bname
.optional_asm_name(),
6426 return this->fndecl_
;
6429 // Get the backend name.
6432 Function_declaration::backend_name(Gogo
* gogo
, Named_object
* no
,
6433 Backend_name
* bname
)
6435 if (!this->asm_name_
.empty())
6436 bname
->set_asm_name(this->asm_name_
);
6440 if (this->fntype_
->is_method())
6441 rtype
= this->fntype_
->receiver()->type();
6442 gogo
->function_backend_name(no
->name(), no
->package(), rtype
, bname
);
6446 // Get the backend representation.
6449 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6451 if (this->fndecl_
== NULL
)
6453 unsigned int flags
=
6454 (Backend::function_is_visible
6455 | Backend::function_is_declaration
6456 | Backend::function_is_inlinable
);
6458 // Let Go code use an asm declaration to pick up a builtin
6460 if (!this->asm_name_
.empty())
6462 Bfunction
* builtin_decl
=
6463 gogo
->backend()->lookup_builtin(this->asm_name_
);
6464 if (builtin_decl
!= NULL
)
6466 this->fndecl_
= builtin_decl
;
6467 return this->fndecl_
;
6470 if (this->asm_name_
== "runtime.gopanic"
6471 || this->asm_name_
.compare(0, 13, "runtime.panic") == 0
6472 || this->asm_name_
.compare(0, 15, "runtime.goPanic") == 0
6473 || this->asm_name_
== "runtime.block")
6474 flags
|= Backend::function_does_not_return
;
6477 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
6480 this->backend_name(gogo
, no
, &bname
);
6482 this->fndecl_
= gogo
->backend()->function(functype
,
6484 bname
.optional_asm_name(),
6489 return this->fndecl_
;
6492 // Build the descriptor for a function declaration. This won't
6493 // necessarily happen if the package has just a declaration for the
6494 // function and no other reference to it, but we may still need the
6495 // descriptor for references from other packages.
6497 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
6499 if (this->descriptor_
!= NULL
)
6501 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
6502 this->descriptor_
->get_backend(&context
);
6506 // Check that the types used in this declaration's signature are defined.
6507 // Reports errors for any undefined type.
6510 Function_declaration::check_types() const
6512 // Calling Type::base will give errors for any undefined types.
6513 Function_type
* fntype
= this->type();
6514 if (fntype
->receiver() != NULL
)
6515 fntype
->receiver()->type()->base();
6516 if (fntype
->parameters() != NULL
)
6518 const Typed_identifier_list
* params
= fntype
->parameters();
6519 for (Typed_identifier_list::const_iterator p
= params
->begin();
6526 // Return the function's decl after it has been built.
6529 Function::get_decl() const
6531 go_assert(this->fndecl_
!= NULL
);
6532 return this->fndecl_
;
6535 // Build the backend representation for the function code.
6538 Function::build(Gogo
* gogo
, Named_object
* named_function
)
6540 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6542 // A list of parameter variables for this function.
6543 std::vector
<Bvariable
*> param_vars
;
6545 // Variables that need to be declared for this function and their
6547 std::vector
<Bvariable
*> vars
;
6548 std::vector
<Expression
*> var_inits
;
6549 std::vector
<Statement
*> var_decls_stmts
;
6550 for (Bindings::const_definitions_iterator p
=
6551 this->block_
->bindings()->begin_definitions();
6552 p
!= this->block_
->bindings()->end_definitions();
6555 Location loc
= (*p
)->location();
6556 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
6558 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6559 Bvariable
* parm_bvar
= bvar
;
6561 // We always pass the receiver to a method as a pointer. If
6562 // the receiver is declared as a non-pointer type, then we
6563 // copy the value into a local variable. For direct interface
6564 // type we pack the pointer into the type.
6565 if ((*p
)->var_value()->is_receiver()
6566 && (*p
)->var_value()->type()->points_to() == NULL
)
6568 std::string name
= (*p
)->name() + ".pointer";
6569 Type
* var_type
= (*p
)->var_value()->type();
6570 Variable
* parm_var
=
6571 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
6573 Named_object
* parm_no
=
6574 Named_object::make_variable(name
, NULL
, parm_var
);
6575 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6577 vars
.push_back(bvar
);
6579 Expression
* parm_ref
=
6580 Expression::make_var_reference(parm_no
, loc
);
6581 Type
* recv_type
= (*p
)->var_value()->type();
6582 if (recv_type
->is_direct_iface_type())
6583 parm_ref
= Expression::pack_direct_iface(recv_type
, parm_ref
, loc
);
6586 Expression::make_dereference(parm_ref
,
6587 Expression::NIL_CHECK_NEEDED
,
6589 if ((*p
)->var_value()->is_in_heap())
6590 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
6591 var_inits
.push_back(parm_ref
);
6593 else if ((*p
)->var_value()->is_in_heap())
6595 // If we take the address of a parameter, then we need
6596 // to copy it into the heap.
6597 std::string parm_name
= (*p
)->name() + ".param";
6598 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
6599 false, true, false, loc
);
6600 Named_object
* parm_no
=
6601 Named_object::make_variable(parm_name
, NULL
, parm_var
);
6602 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6604 vars
.push_back(bvar
);
6605 Expression
* var_ref
=
6606 Expression::make_var_reference(parm_no
, loc
);
6607 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
6608 var_inits
.push_back(var_ref
);
6610 param_vars
.push_back(parm_bvar
);
6612 else if ((*p
)->is_result_variable())
6614 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6616 Type
* type
= (*p
)->result_var_value()->type();
6618 if (!(*p
)->result_var_value()->is_in_heap())
6620 Btype
* btype
= type
->get_backend(gogo
);
6621 Bexpression
* binit
= gogo
->backend()->zero_expression(btype
);
6622 init
= Expression::make_backend(binit
, type
, loc
);
6625 init
= Expression::make_allocation(type
, loc
);
6627 vars
.push_back(bvar
);
6628 var_inits
.push_back(init
);
6630 else if (this->defer_stack_
!= NULL
6631 && (*p
)->is_variable()
6632 && (*p
)->var_value()->is_non_escaping_address_taken()
6633 && !(*p
)->var_value()->is_in_heap())
6635 // Local variable captured by deferred closure needs to be live
6636 // until the end of the function. We create a top-level
6637 // declaration for it.
6638 // TODO: we don't need to do this if the variable is not captured
6639 // by the defer closure. There is no easy way to check it here,
6640 // so we do this for all address-taken variables for now.
6641 Variable
* var
= (*p
)->var_value();
6642 Temporary_statement
* ts
=
6643 Statement::make_temporary(var
->type(), NULL
, var
->location());
6644 ts
->set_is_address_taken();
6645 var
->set_toplevel_decl(ts
);
6646 var_decls_stmts
.push_back(ts
);
6649 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
6651 go_assert(saw_errors());
6655 // If we need a closure variable, make sure to create it.
6656 // It gets installed in the function as a side effect of creation.
6657 if (this->closure_var_
!= NULL
)
6659 go_assert(this->closure_var_
->var_value()->is_closure());
6660 this->closure_var_
->get_backend_variable(gogo
, named_function
);
6663 if (this->block_
!= NULL
)
6665 // Declare variables if necessary.
6666 Bblock
* var_decls
= NULL
;
6667 std::vector
<Bstatement
*> var_decls_bstmt_list
;
6668 Bstatement
* defer_init
= NULL
;
6669 if (!vars
.empty() || this->defer_stack_
!= NULL
)
6672 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
6673 this->block_
->start_location(),
6674 this->block_
->end_location());
6676 if (this->defer_stack_
!= NULL
)
6678 Translate_context
dcontext(gogo
, named_function
, this->block_
,
6680 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
6681 var_decls_bstmt_list
.push_back(defer_init
);
6682 for (std::vector
<Statement
*>::iterator p
= var_decls_stmts
.begin();
6683 p
!= var_decls_stmts
.end();
6686 Bstatement
* bstmt
= (*p
)->get_backend(&dcontext
);
6687 var_decls_bstmt_list
.push_back(bstmt
);
6692 // Build the backend representation for all the statements in the
6694 Translate_context
bcontext(gogo
, named_function
, NULL
, NULL
);
6695 Bblock
* code_block
= this->block_
->get_backend(&bcontext
);
6697 // Initialize variables if necessary.
6698 Translate_context
icontext(gogo
, named_function
, this->block_
,
6700 std::vector
<Bstatement
*> init
;
6701 go_assert(vars
.size() == var_inits
.size());
6702 for (size_t i
= 0; i
< vars
.size(); ++i
)
6704 Bexpression
* binit
= var_inits
[i
]->get_backend(&icontext
);
6705 Bstatement
* init_stmt
=
6706 gogo
->backend()->init_statement(this->fndecl_
, vars
[i
],
6708 init
.push_back(init_stmt
);
6710 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
6712 // Initialize all variables before executing this code block.
6713 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
6714 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
6716 // If we have a defer stack, initialize it at the start of a
6718 Bstatement
* except
= NULL
;
6719 Bstatement
* fini
= NULL
;
6720 if (defer_init
!= NULL
)
6722 // Clean up the defer stack when we leave the function.
6723 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
6725 // Wrap the code for this function in an exception handler to handle
6728 gogo
->backend()->exception_handler_statement(code_stmt
,
6733 // Stick the code into the block we built for the receiver, if
6735 if (var_decls
!= NULL
)
6737 var_decls_bstmt_list
.push_back(code_stmt
);
6738 gogo
->backend()->block_add_statements(var_decls
, var_decls_bstmt_list
);
6739 code_stmt
= gogo
->backend()->block_statement(var_decls
);
6742 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
6744 go_assert(saw_errors());
6749 // If we created a descriptor for the function, make sure we emit it.
6750 if (this->descriptor_
!= NULL
)
6752 Translate_context
dcontext(gogo
, NULL
, NULL
, NULL
);
6753 this->descriptor_
->get_backend(&dcontext
);
6757 // Build the wrappers around function code needed if the function has
6758 // any defer statements. This sets *EXCEPT to an exception handler
6759 // and *FINI to a finally handler.
6762 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
6763 Bstatement
** except
, Bstatement
** fini
)
6765 Location end_loc
= this->block_
->end_location();
6767 // Add an exception handler. This is used if a panic occurs. Its
6768 // purpose is to stop the stack unwinding if a deferred function
6769 // calls recover. There are more details in
6770 // libgo/runtime/go-unwind.c.
6772 std::vector
<Bstatement
*> stmts
;
6773 Expression
* call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6774 this->defer_stack(end_loc
));
6775 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6776 Bexpression
* defer
= call
->get_backend(&context
);
6777 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, defer
));
6779 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6780 if (ret_bstmt
!= NULL
)
6781 stmts
.push_back(ret_bstmt
);
6783 go_assert(*except
== NULL
);
6784 *except
= gogo
->backend()->statement_list(stmts
);
6786 call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6787 this->defer_stack(end_loc
));
6788 defer
= call
->get_backend(&context
);
6790 call
= Runtime::make_call(Runtime::DEFERRETURN
, end_loc
, 1,
6791 this->defer_stack(end_loc
));
6792 Bexpression
* undefer
= call
->get_backend(&context
);
6793 Bstatement
* function_defer
=
6794 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
6796 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
6797 if (this->type_
->results() != NULL
6798 && !this->type_
->results()->empty()
6799 && !this->type_
->results()->front().name().empty())
6801 // If the result variables are named, and we are returning from
6802 // this function rather than panicing through it, we need to
6803 // return them again, because they might have been changed by a
6804 // defer function. The runtime routines set the defer_stack
6805 // variable to true if we are returning from this function.
6807 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6808 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
6810 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
6812 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
6813 Bexpression
* bref
= ref
->get_backend(&context
);
6814 ret
= gogo
->backend()->conditional_expression(this->fndecl_
,
6815 NULL
, bref
, ret
, NULL
,
6817 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, ret
));
6820 go_assert(*fini
== NULL
);
6821 *fini
= gogo
->backend()->statement_list(stmts
);
6824 // Return the statement that assigns values to this function's result struct.
6827 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
6828 Location location
) const
6830 const Typed_identifier_list
* results
= this->type_
->results();
6831 if (results
== NULL
|| results
->empty())
6834 go_assert(this->results_
!= NULL
);
6835 if (this->results_
->size() != results
->size())
6837 go_assert(saw_errors());
6838 return gogo
->backend()->error_statement();
6841 std::vector
<Bexpression
*> vals(results
->size());
6842 for (size_t i
= 0; i
< vals
.size(); ++i
)
6844 Named_object
* no
= (*this->results_
)[i
];
6845 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
6846 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
6847 if (no
->result_var_value()->is_in_heap())
6849 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
6850 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
6854 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
6859 Block::Block(Block
* enclosing
, Location location
)
6860 : enclosing_(enclosing
), statements_(),
6861 bindings_(new Bindings(enclosing
== NULL
6863 : enclosing
->bindings())),
6864 start_location_(location
),
6865 end_location_(Linemap::unknown_location())
6869 // Add a statement to a block.
6872 Block::add_statement(Statement
* statement
)
6874 this->statements_
.push_back(statement
);
6877 // Add a statement to the front of a block. This is slow but is only
6878 // used for reference counts of parameters.
6881 Block::add_statement_at_front(Statement
* statement
)
6883 this->statements_
.insert(this->statements_
.begin(), statement
);
6886 // Replace a statement in a block.
6889 Block::replace_statement(size_t index
, Statement
* s
)
6891 go_assert(index
< this->statements_
.size());
6892 this->statements_
[index
] = s
;
6895 // Add a statement before another statement.
6898 Block::insert_statement_before(size_t index
, Statement
* s
)
6900 go_assert(index
< this->statements_
.size());
6901 this->statements_
.insert(this->statements_
.begin() + index
, s
);
6904 // Add a statement after another statement.
6907 Block::insert_statement_after(size_t index
, Statement
* s
)
6909 go_assert(index
< this->statements_
.size());
6910 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
6913 // Traverse the tree.
6916 Block::traverse(Traverse
* traverse
)
6918 unsigned int traverse_mask
= traverse
->traverse_mask();
6920 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
6922 int t
= traverse
->block(this);
6923 if (t
== TRAVERSE_EXIT
)
6924 return TRAVERSE_EXIT
;
6925 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
6926 return TRAVERSE_CONTINUE
;
6930 & (Traverse::traverse_variables
6931 | Traverse::traverse_constants
6932 | Traverse::traverse_expressions
6933 | Traverse::traverse_types
)) != 0)
6935 for (Bindings::const_definitions_iterator pb
=
6936 this->bindings_
->begin_definitions();
6937 pb
!= this->bindings_
->end_definitions();
6940 if ((*pb
)->traverse(traverse
, false) == TRAVERSE_EXIT
)
6941 return TRAVERSE_EXIT
;
6945 // No point in checking traverse_mask here--if we got here we always
6946 // want to walk the statements. The traversal can insert new
6947 // statements before or after the current statement. Inserting
6948 // statements before the current statement requires updating I via
6949 // the pointer; those statements will not be traversed. Any new
6950 // statements inserted after the current statement will be traversed
6952 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
6954 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
6955 return TRAVERSE_EXIT
;
6958 return TRAVERSE_CONTINUE
;
6961 // Work out types for unspecified variables and constants.
6964 Block::determine_types()
6966 for (Bindings::const_definitions_iterator pb
=
6967 this->bindings_
->begin_definitions();
6968 pb
!= this->bindings_
->end_definitions();
6971 if ((*pb
)->is_variable())
6972 (*pb
)->var_value()->determine_type();
6973 else if ((*pb
)->is_const())
6974 (*pb
)->const_value()->determine_type();
6977 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
6978 ps
!= this->statements_
.end();
6980 (*ps
)->determine_types();
6983 // Return true if the statements in this block may fall through.
6986 Block::may_fall_through() const
6988 if (this->statements_
.empty())
6990 return this->statements_
.back()->may_fall_through();
6993 // Write export data for a block.
6996 Block::export_block(Export_function_body
* efb
)
6998 for (Block::iterator p
= this->begin();
7004 efb
->increment_indent();
7005 (*p
)->export_statement(efb
);
7006 efb
->decrement_indent();
7008 Location loc
= (*p
)->location();
7009 if ((*p
)->is_block_statement())
7011 // For a block we put the start location on the first brace
7012 // in Block_statement::do_export_statement. Here we put the
7013 // end location on the final brace.
7014 loc
= (*p
)->block_statement()->block()->end_location();
7017 snprintf(buf
, sizeof buf
, " //%d\n", Linemap::location_to_line(loc
));
7018 efb
->write_c_string(buf
);
7022 // Add exported block data to SET, reading from BODY starting at OFF.
7023 // Returns whether the import succeeded.
7026 Block::import_block(Block
* set
, Import_function_body
*ifb
, Location loc
)
7028 Location eloc
= ifb
->location();
7029 Location sloc
= loc
;
7030 const std::string
& body(ifb
->body());
7031 size_t off
= ifb
->off();
7032 while (off
< body
.length())
7034 int indent
= ifb
->indent();
7035 if (off
+ indent
>= body
.length())
7038 "invalid export data for %qs: insufficient indentation",
7039 ifb
->name().c_str());
7042 for (int i
= 0; i
< indent
- 1; i
++)
7044 if (body
[off
+ i
] != ' ')
7047 "invalid export data for %qs: bad indentation",
7048 ifb
->name().c_str());
7053 bool at_end
= false;
7054 if (body
[off
+ indent
- 1] == '}')
7056 else if (body
[off
+ indent
- 1] != ' ')
7059 "invalid export data for %qs: bad indentation",
7060 ifb
->name().c_str());
7066 size_t nl
= body
.find('\n', off
);
7067 if (nl
== std::string::npos
)
7069 go_error_at(eloc
, "invalid export data for %qs: missing newline",
7070 ifb
->name().c_str());
7074 size_t lineno_pos
= body
.find(" //", off
);
7075 if (lineno_pos
== std::string::npos
|| lineno_pos
>= nl
)
7077 go_error_at(eloc
, "invalid export data for %qs: missing line number",
7078 ifb
->name().c_str());
7082 unsigned int lineno
= 0;
7083 for (size_t i
= lineno_pos
+ 3; i
< nl
; ++i
)
7086 if (c
< '0' || c
> '9')
7089 "invalid export data for %qs: invalid line number",
7090 ifb
->name().c_str());
7093 lineno
= lineno
* 10 + c
- '0';
7096 ifb
->gogo()->linemap()->start_line(lineno
, 1);
7097 sloc
= ifb
->gogo()->linemap()->get_location(0);
7101 // An if statement can have an "else" following the "}", in
7102 // which case we want to leave the offset where it is, just
7103 // after the "}". We don't get the block ending location
7104 // quite right for if statements.
7105 if (body
.compare(off
, 6, " else ") != 0)
7111 Statement
* s
= Statement::import_statement(ifb
, sloc
);
7115 set
->add_statement(s
);
7117 size_t at
= ifb
->off();
7125 set
->set_end_location(sloc
);
7129 // Convert a block to the backend representation.
7132 Block::get_backend(Translate_context
* context
)
7134 Gogo
* gogo
= context
->gogo();
7135 Named_object
* function
= context
->function();
7136 std::vector
<Bvariable
*> vars
;
7137 vars
.reserve(this->bindings_
->size_definitions());
7138 for (Bindings::const_definitions_iterator pv
=
7139 this->bindings_
->begin_definitions();
7140 pv
!= this->bindings_
->end_definitions();
7143 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
7144 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
7147 go_assert(function
!= NULL
);
7148 Bfunction
* bfunction
=
7149 function
->func_value()->get_or_make_decl(gogo
, function
);
7150 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
7151 vars
, this->start_location_
,
7152 this->end_location_
);
7154 Translate_context
subcontext(gogo
, function
, this, ret
);
7155 std::vector
<Bstatement
*> bstatements
;
7156 bstatements
.reserve(this->statements_
.size());
7157 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
7158 p
!= this->statements_
.end();
7160 bstatements
.push_back((*p
)->get_backend(&subcontext
));
7162 context
->backend()->block_add_statements(ret
, bstatements
);
7167 // Class Bindings_snapshot.
7169 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
7170 : block_(b
), counts_(), location_(location
)
7174 this->counts_
.push_back(b
->bindings()->size_definitions());
7179 // Report errors appropriate for a goto from B to this.
7182 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
7185 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
7187 this->check_goto_defs(loc
, this->block_
,
7188 this->block_
->bindings()->size_definitions(),
7192 // Report errors appropriate for a goto from this to B.
7195 Bindings_snapshot::check_goto_to(const Block
* b
)
7198 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
7200 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
7201 b
->bindings()->size_definitions());
7204 // Report errors appropriate for a goto at LOC from BFROM to BTO.
7205 // Return true if all is well, false if we reported an error. If this
7206 // returns true, it sets *PINDEX to the number of blocks BTO is above
7210 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
7211 const Block
* bto
, size_t* pindex
)
7213 // It is an error if BTO is not either BFROM or above BFROM.
7215 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
7219 go_error_at(loc
, "goto jumps into block");
7220 go_inform(bto
->start_location(), "goto target block starts here");
7228 // Report errors appropriate for a goto at LOC ending at BLOCK, where
7229 // CFROM is the number of names defined at the point of the goto and
7230 // CTO is the number of names defined at the point of the label.
7233 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
7234 size_t cfrom
, size_t cto
)
7238 Bindings::const_definitions_iterator p
=
7239 block
->bindings()->begin_definitions();
7240 for (size_t i
= 0; i
< cfrom
; ++i
)
7242 go_assert(p
!= block
->bindings()->end_definitions());
7245 go_assert(p
!= block
->bindings()->end_definitions());
7247 for (; p
!= block
->bindings()->end_definitions(); ++p
)
7249 if ((*p
)->is_variable())
7251 std::string n
= (*p
)->message_name();
7252 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
7253 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
7259 // Class Function_declaration.
7261 // Whether this declares a method.
7264 Function_declaration::is_method() const
7266 return this->fntype_
->is_method();
7269 // Whether this method should not be included in the type descriptor.
7272 Function_declaration::nointerface() const
7274 go_assert(this->is_method());
7275 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
7278 // Record that this method should not be included in the type
7282 Function_declaration::set_nointerface()
7284 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
7287 // Set the receiver type. This is used to remove aliases.
7290 Function_declaration::set_receiver_type(Type
* rtype
)
7292 Function_type
* oft
= this->fntype_
;
7293 Typed_identifier
* rec
= new Typed_identifier(oft
->receiver()->name(),
7295 oft
->receiver()->location());
7296 Typed_identifier_list
* parameters
= NULL
;
7297 if (oft
->parameters() != NULL
)
7298 parameters
= oft
->parameters()->copy();
7299 Typed_identifier_list
* results
= NULL
;
7300 if (oft
->results() != NULL
)
7301 results
= oft
->results()->copy();
7302 Function_type
* nft
= Type::make_function_type(rec
, parameters
, results
,
7304 this->fntype_
= nft
;
7307 // Import an inlinable function. This is used for an inlinable
7308 // function whose body is recorded in the export data. Parse the
7309 // export data into a Block and create a regular function using that
7310 // Block as its body. Redeclare this function declaration as the
7314 Function_declaration::import_function_body(Gogo
* gogo
, Named_object
* no
)
7316 go_assert(no
->func_declaration_value() == this);
7317 go_assert(no
->package() != NULL
);
7318 const std::string
& body(this->imported_body_
);
7319 go_assert(!body
.empty());
7321 // Read the "//FILE:LINE" comment starts the export data.
7324 if (this->is_method())
7327 for (; i
< indent
; i
++)
7329 if (body
.at(i
) != ' ')
7331 go_error_at(this->location_
,
7332 "invalid export body for %qs: bad initial indentation",
7333 no
->message_name().c_str());
7338 if (body
.substr(i
, 2) != "//")
7340 go_error_at(this->location_
,
7341 "invalid export body for %qs: missing file comment",
7342 no
->message_name().c_str());
7346 size_t colon
= body
.find(':', i
+ 2);
7347 size_t nl
= body
.find('\n', i
+ 2);
7348 if (nl
== std::string::npos
)
7350 go_error_at(this->location_
,
7351 "invalid export body for %qs: missing file name",
7352 no
->message_name().c_str());
7355 if (colon
== std::string::npos
|| nl
< colon
)
7357 go_error_at(this->location_
,
7358 "invalid export body for %qs: missing initial line number",
7359 no
->message_name().c_str());
7363 std::string file
= body
.substr(i
+ 2, colon
- (i
+ 2));
7364 std::string linestr
= body
.substr(colon
+ 1, nl
- (colon
+ 1));
7366 long linenol
= strtol(linestr
.c_str(), &end
, 10);
7369 go_error_at(this->location_
,
7370 "invalid export body for %qs: invalid initial line number",
7371 no
->message_name().c_str());
7374 unsigned int lineno
= static_cast<unsigned int>(linenol
);
7376 // Turn the file/line into a location.
7378 char* alc
= new char[file
.length() + 1];
7379 memcpy(alc
, file
.data(), file
.length());
7380 alc
[file
.length()] = '\0';
7381 gogo
->linemap()->start_file(alc
, lineno
);
7382 gogo
->linemap()->start_line(lineno
, 1);
7383 Location start_loc
= gogo
->linemap()->get_location(0);
7385 // Define the function with an outer block that declares the
7388 Function_type
* fntype
= this->fntype_
;
7390 Block
* outer
= new Block(NULL
, start_loc
);
7392 Function
* fn
= new Function(fntype
, NULL
, outer
, start_loc
);
7393 fn
->set_is_inline_only();
7395 if (fntype
->is_method())
7397 if (this->nointerface())
7398 fn
->set_nointerface();
7399 const Typed_identifier
* receiver
= fntype
->receiver();
7400 Variable
* recv_param
= new Variable(receiver
->type(), NULL
, false,
7401 true, true, start_loc
);
7403 std::string rname
= receiver
->name();
7404 unsigned rcounter
= 0;
7406 // We need to give a nameless receiver a name to avoid having it
7407 // clash with some other nameless param. FIXME.
7408 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
7410 outer
->bindings()->add_variable(rname
, NULL
, recv_param
);
7413 const Typed_identifier_list
* params
= fntype
->parameters();
7414 bool is_varargs
= fntype
->is_varargs();
7415 unsigned pcounter
= 0;
7418 for (Typed_identifier_list::const_iterator p
= params
->begin();
7422 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
7424 if (is_varargs
&& p
+ 1 == params
->end())
7425 param
->set_is_varargs_parameter();
7427 std::string pname
= p
->name();
7429 // We need to give each nameless parameter a non-empty name to avoid
7430 // having it clash with some other nameless param. FIXME.
7431 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
7433 outer
->bindings()->add_variable(pname
, NULL
, param
);
7437 fn
->create_result_variables(gogo
);
7439 if (!fntype
->is_method())
7441 const Package
* package
= no
->package();
7442 no
= package
->bindings()->add_function(no
->name(), package
, fn
);
7446 Named_type
* rtype
= fntype
->receiver()->type()->deref()->named_type();
7447 go_assert(rtype
!= NULL
);
7448 no
= rtype
->add_method(no
->name(), fn
);
7449 const Package
* package
= rtype
->named_object()->package();
7450 package
->bindings()->add_method(no
);
7453 Import_function_body
ifb(gogo
, this->imp_
, no
, body
, nl
+ 1, outer
, indent
);
7455 if (!Block::import_block(outer
, &ifb
, start_loc
))
7458 gogo
->lower_block(no
, outer
);
7459 outer
->determine_types();
7461 gogo
->add_imported_inline_function(no
);
7464 // Return the function descriptor.
7467 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
7469 go_assert(!this->fntype_
->is_method());
7470 if (this->descriptor_
== NULL
)
7471 this->descriptor_
= Expression::make_func_descriptor(no
);
7472 return this->descriptor_
;
7477 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
7478 bool is_parameter
, bool is_receiver
,
7480 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
7481 toplevel_decl_(NULL
), init_refs_(NULL
), embeds_(NULL
), backend_(NULL
),
7482 is_global_(is_global
), is_parameter_(is_parameter
), is_closure_(false),
7483 is_receiver_(is_receiver
), is_varargs_parameter_(false),
7484 is_global_sink_(false), is_used_(false), is_address_taken_(false),
7485 is_non_escaping_address_taken_(false), seen_(false),
7486 init_is_lowered_(false), init_is_flattened_(false),
7487 type_from_init_tuple_(false), type_from_range_index_(false),
7488 type_from_range_value_(false), type_from_chan_element_(false),
7489 is_type_switch_var_(false), determined_type_(false),
7490 in_unique_section_(false), is_referenced_by_inline_(false)
7492 go_assert(type
!= NULL
|| init
!= NULL
);
7493 go_assert(!is_parameter
|| init
== NULL
);
7496 // Traverse the initializer expression.
7499 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
7501 if (this->preinit_
!= NULL
)
7503 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
7504 return TRAVERSE_EXIT
;
7506 if (this->init_
!= NULL
7508 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
7511 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
7512 return TRAVERSE_EXIT
;
7514 return TRAVERSE_CONTINUE
;
7517 // Lower the initialization expression after parsing is complete.
7520 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
7521 Statement_inserter
* inserter
)
7523 Named_object
* dep
= gogo
->var_depends_on(this);
7524 if (dep
!= NULL
&& dep
->is_variable())
7525 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
7527 if (this->embeds_
!= NULL
)
7529 // Now that we have seen any possible type aliases, convert the
7530 // go:embed directives into an initializer.
7531 go_assert(this->init_
== NULL
&& this->type_
!= NULL
);
7532 this->init_
= gogo
->initializer_for_embeds(this->type_
, this->embeds_
,
7534 delete this->embeds_
;
7535 this->embeds_
= NULL
;
7538 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
7542 // We will give an error elsewhere, this is just to prevent
7543 // an infinite loop.
7548 Statement_inserter global_inserter
;
7549 if (this->is_global_
)
7551 global_inserter
= Statement_inserter(gogo
, this);
7552 inserter
= &global_inserter
;
7555 gogo
->lower_expression(function
, inserter
, &this->init_
);
7557 this->seen_
= false;
7559 this->init_is_lowered_
= true;
7563 // Flatten the initialization expression after ordering evaluations.
7566 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
7567 Statement_inserter
* inserter
)
7569 Named_object
* dep
= gogo
->var_depends_on(this);
7570 if (dep
!= NULL
&& dep
->is_variable())
7571 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
7573 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
7577 // We will give an error elsewhere, this is just to prevent
7578 // an infinite loop.
7583 Statement_inserter global_inserter
;
7584 if (this->is_global_
)
7586 global_inserter
= Statement_inserter(gogo
, this);
7587 inserter
= &global_inserter
;
7590 gogo
->flatten_expression(function
, inserter
, &this->init_
);
7592 // If an interface conversion is needed, we need a temporary
7594 if (this->type_
!= NULL
7595 && !Type::are_identical(this->type_
, this->init_
->type(),
7596 Type::COMPARE_ERRORS
| Type::COMPARE_TAGS
,
7598 && this->init_
->type()->interface_type() != NULL
7599 && !this->init_
->is_multi_eval_safe())
7601 Temporary_statement
* temp
=
7602 Statement::make_temporary(NULL
, this->init_
, this->location_
);
7603 inserter
->insert(temp
);
7604 this->init_
= Expression::make_temporary_reference(temp
,
7608 this->seen_
= false;
7609 this->init_is_flattened_
= true;
7613 // Get the preinit block.
7616 Variable::preinit_block(Gogo
* gogo
)
7618 go_assert(this->is_global_
);
7619 if (this->preinit_
== NULL
)
7620 this->preinit_
= new Block(NULL
, this->location());
7622 // If a global variable has a preinitialization statement, then we
7623 // need to have an initialization function.
7624 gogo
->set_need_init_fn();
7626 return this->preinit_
;
7629 // Add a statement to be run before the initialization expression.
7632 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
7634 Block
* b
= this->preinit_block(gogo
);
7635 b
->add_statement(s
);
7636 b
->set_end_location(s
->location());
7639 // Whether this variable has a type.
7642 Variable::has_type() const
7644 if (this->type_
== NULL
)
7647 // A variable created in a type switch case nil does not actually
7648 // have a type yet. It will be changed to use the initializer's
7649 // type in determine_type.
7650 if (this->is_type_switch_var_
7651 && this->type_
->is_nil_constant_as_type())
7657 // In an assignment which sets a variable to a tuple of EXPR, return
7658 // the type of the first element of the tuple.
7661 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
7663 if (expr
->map_index_expression() != NULL
)
7665 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
7667 return Type::make_error_type();
7668 return mt
->val_type();
7670 else if (expr
->receive_expression() != NULL
)
7672 Expression
* channel
= expr
->receive_expression()->channel();
7673 Type
* channel_type
= channel
->type();
7674 if (channel_type
->channel_type() == NULL
)
7675 return Type::make_error_type();
7676 return channel_type
->channel_type()->element_type();
7681 go_error_at(this->location(), "invalid tuple definition");
7682 return Type::make_error_type();
7686 // Given EXPR used in a range clause, return either the index type or
7687 // the value type of the range, depending upon GET_INDEX_TYPE.
7690 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
7691 bool report_error
) const
7693 Type
* t
= expr
->type();
7694 if (t
->array_type() != NULL
7695 || (t
->points_to() != NULL
7696 && t
->points_to()->array_type() != NULL
7697 && !t
->points_to()->is_slice_type()))
7700 return Type::lookup_integer_type("int");
7702 return t
->deref()->array_type()->element_type();
7704 else if (t
->is_string_type())
7707 return Type::lookup_integer_type("int");
7709 return Type::lookup_integer_type("int32");
7711 else if (t
->map_type() != NULL
)
7714 return t
->map_type()->key_type();
7716 return t
->map_type()->val_type();
7718 else if (t
->channel_type() != NULL
)
7721 return t
->channel_type()->element_type();
7725 go_error_at(this->location(),
7726 ("invalid definition of value variable "
7727 "for channel range"));
7728 return Type::make_error_type();
7734 go_error_at(this->location(), "invalid type for range clause");
7735 return Type::make_error_type();
7739 // EXPR should be a channel. Return the channel's element type.
7742 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
7744 Type
* t
= expr
->type();
7745 if (t
->channel_type() != NULL
)
7746 return t
->channel_type()->element_type();
7750 go_error_at(this->location(), "expected channel");
7751 return Type::make_error_type();
7755 // Return the type of the Variable. This may be called before
7756 // Variable::determine_type is called, which means that we may need to
7757 // get the type from the initializer. FIXME: If we combine lowering
7758 // with type determination, then this should be unnecessary.
7763 // A variable in a type switch with a nil case will have the wrong
7764 // type here. This gets fixed up in determine_type, below.
7765 Type
* type
= this->type_
;
7766 Expression
* init
= this->init_
;
7767 if (this->is_type_switch_var_
7769 && this->type_
->is_nil_constant_as_type())
7771 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7772 go_assert(tge
!= NULL
);
7779 if (this->type_
== NULL
|| !this->type_
->is_error_type())
7781 go_error_at(this->location_
, "variable initializer refers to itself");
7782 this->type_
= Type::make_error_type();
7791 else if (this->type_from_init_tuple_
)
7792 type
= this->type_from_tuple(init
, false);
7793 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7794 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
7795 else if (this->type_from_chan_element_
)
7796 type
= this->type_from_chan_element(init
, false);
7799 go_assert(init
!= NULL
);
7800 type
= init
->type();
7801 go_assert(type
!= NULL
);
7803 // Variables should not have abstract types.
7804 if (type
->is_abstract())
7805 type
= type
->make_non_abstract_type();
7807 if (type
->is_void_type())
7808 type
= Type::make_error_type();
7811 this->seen_
= false;
7816 // Fetch the type from a const pointer, in which case it should have
7817 // been set already.
7820 Variable::type() const
7822 go_assert(this->type_
!= NULL
);
7826 // Set the type if necessary.
7829 Variable::determine_type()
7831 if (this->determined_type_
)
7833 this->determined_type_
= true;
7835 if (this->preinit_
!= NULL
)
7836 this->preinit_
->determine_types();
7838 // A variable in a type switch with a nil case will have the wrong
7839 // type here. It will have an initializer which is a type guard.
7840 // We want to initialize it to the value without the type guard, and
7841 // use the type of that value as well.
7842 if (this->is_type_switch_var_
7843 && this->type_
!= NULL
7844 && this->type_
->is_nil_constant_as_type())
7846 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7847 go_assert(tge
!= NULL
);
7849 this->init_
= tge
->expr();
7852 if (this->init_
== NULL
)
7853 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
7854 else if (this->type_from_init_tuple_
)
7856 Expression
*init
= this->init_
;
7857 init
->determine_type_no_context();
7858 this->type_
= this->type_from_tuple(init
, true);
7861 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7863 Expression
* init
= this->init_
;
7864 init
->determine_type_no_context();
7865 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
7869 else if (this->type_from_chan_element_
)
7871 Expression
* init
= this->init_
;
7872 init
->determine_type_no_context();
7873 this->type_
= this->type_from_chan_element(init
, true);
7878 Type_context
context(this->type_
, false);
7879 this->init_
->determine_type(&context
);
7880 if (this->type_
== NULL
)
7882 Type
* type
= this->init_
->type();
7883 go_assert(type
!= NULL
);
7884 if (type
->is_abstract())
7885 type
= type
->make_non_abstract_type();
7887 if (type
->is_void_type())
7889 go_error_at(this->location_
, "variable has no type");
7890 type
= Type::make_error_type();
7892 else if (type
->is_nil_type())
7894 go_error_at(this->location_
, "variable defined to nil type");
7895 type
= Type::make_error_type();
7897 else if (type
->is_call_multiple_result_type())
7899 go_error_at(this->location_
,
7900 "single variable set to multiple-value function call");
7901 type
= Type::make_error_type();
7909 // Get the initial value of a variable. This does not
7910 // consider whether the variable is in the heap--it returns the
7911 // initial value as though it were always stored in the stack.
7914 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
7916 go_assert(this->preinit_
== NULL
);
7917 Location loc
= this->location();
7918 if (this->init_
== NULL
)
7920 go_assert(!this->is_parameter_
);
7921 if (this->is_global_
|| this->is_in_heap())
7923 Btype
* btype
= this->type()->get_backend(gogo
);
7924 return gogo
->backend()->zero_expression(btype
);
7928 Translate_context
context(gogo
, function
, NULL
, NULL
);
7929 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
7930 return init
->get_backend(&context
);
7934 // Get the initial value of a variable when a block is required.
7935 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7938 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
7939 Bvariable
* var_decl
)
7941 go_assert(this->preinit_
!= NULL
);
7943 // We want to add the variable assignment to the end of the preinit
7946 Translate_context
context(gogo
, function
, NULL
, NULL
);
7947 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
7948 Bfunction
* bfunction
=
7949 function
->func_value()->get_or_make_decl(gogo
, function
);
7951 // It's possible to have pre-init statements without an initializer
7952 // if the pre-init statements set the variable.
7953 Bstatement
* decl_init
= NULL
;
7954 if (this->init_
!= NULL
)
7956 if (var_decl
== NULL
)
7958 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
7959 decl_init
= gogo
->backend()->expression_statement(bfunction
,
7964 Location loc
= this->location();
7965 Expression
* val_expr
=
7966 Expression::make_cast(this->type(), this->init_
, loc
);
7967 Bexpression
* val
= val_expr
->get_backend(&context
);
7968 Bexpression
* var_ref
=
7969 gogo
->backend()->var_expression(var_decl
, loc
);
7970 decl_init
= gogo
->backend()->assignment_statement(bfunction
, var_ref
,
7974 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
7975 if (decl_init
!= NULL
)
7976 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
7980 // Add an initializer reference.
7983 Variable::add_init_ref(Named_object
* var
)
7985 if (this->init_refs_
== NULL
)
7986 this->init_refs_
= new std::vector
<Named_object
*>;
7987 this->init_refs_
->push_back(var
);
7990 // Export the variable
7993 Variable::export_var(Export
* exp
, const Named_object
* no
) const
7995 go_assert(this->is_global_
);
7996 exp
->write_c_string("var ");
7997 if (no
->package() != NULL
)
8000 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
8001 exp
->write_c_string(buf
);
8004 if (!Gogo::is_hidden_name(no
->name()))
8005 exp
->write_string(no
->name());
8008 exp
->write_c_string(".");
8009 exp
->write_string(Gogo::unpack_hidden_name(no
->name()));
8012 exp
->write_c_string(" ");
8013 exp
->write_type(this->type());
8014 exp
->write_c_string("\n");
8017 // Import a variable.
8020 Variable::import_var(Import
* imp
, std::string
* pname
, Package
** ppkg
,
8021 bool* pis_exported
, Type
** ptype
)
8023 imp
->require_c_string("var ");
8024 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
8026 go_error_at(imp
->location(),
8027 "import error at %d: bad variable name in export data",
8031 imp
->require_c_string(" ");
8032 *ptype
= imp
->read_type();
8033 imp
->require_semicolon_if_old_version();
8034 imp
->require_c_string("\n");
8038 // Convert a variable to the backend representation.
8041 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
8042 const Package
* package
, const std::string
& name
)
8044 if (this->backend_
== NULL
)
8046 Backend
* backend
= gogo
->backend();
8047 Type
* type
= this->type_
;
8048 if (type
->is_error_type()
8049 || (type
->is_undefined()
8050 && (!this->is_global_
|| package
== NULL
)))
8051 this->backend_
= backend
->error_variable();
8054 bool is_parameter
= this->is_parameter_
;
8055 if (this->is_receiver_
&& type
->points_to() == NULL
)
8056 is_parameter
= false;
8057 if (this->is_in_heap())
8059 is_parameter
= false;
8060 type
= Type::make_pointer_type(type
);
8063 Btype
* btype
= type
->get_backend(gogo
);
8066 if (Map_type::is_zero_value(this))
8067 bvar
= Map_type::backend_zero_value(gogo
);
8068 else if (this->is_global_
)
8071 gogo
->global_var_backend_name(name
, package
, &bname
);
8073 bool is_hidden
= Gogo::is_hidden_name(name
);
8074 // Hack to export runtime.writeBarrier. FIXME.
8075 // This is because go:linkname doesn't work on variables.
8076 if (gogo
->compiling_runtime()
8077 && bname
.name() == "runtime.writeBarrier")
8080 // If an inline body refers to this variable, then it
8081 // needs to be visible in the symbol table.
8082 if (this->is_referenced_by_inline_
)
8085 // If this variable is in a different package, then it
8086 // can't be treated as a hidden symbol. This case can
8087 // arise when an inlined function refers to a
8088 // package-scope unexported variable.
8089 if (package
!= NULL
)
8092 unsigned int flags
= 0;
8093 if (this->is_address_taken_
8094 || this->is_non_escaping_address_taken_
)
8095 flags
|= Backend::variable_address_is_taken
;
8096 if (package
!= NULL
)
8097 flags
|= Backend::variable_is_external
;
8099 flags
|= Backend::variable_is_hidden
;
8100 if (this->in_unique_section_
)
8101 flags
|= Backend::variable_in_unique_section
;
8103 // For some reason asm_name can't be the empty string
8104 // for global_variable, so we call asm_name rather than
8105 // optional_asm_name here. FIXME.
8107 bvar
= backend
->global_variable(bname
.name(),
8112 else if (function
== NULL
)
8114 go_assert(saw_errors());
8115 bvar
= backend
->error_variable();
8119 const std::string n
= Gogo::unpack_hidden_name(name
);
8120 Bfunction
* bfunction
= function
->func_value()->get_decl();
8121 unsigned int flags
= 0;
8122 if (this->is_non_escaping_address_taken_
8123 && !this->is_in_heap())
8124 flags
|= Backend::variable_address_is_taken
;
8125 if (this->is_closure())
8126 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
8127 flags
, this->location_
);
8128 else if (is_parameter
)
8129 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
8130 flags
, this->location_
);
8133 Bvariable
* bvar_decl
= NULL
;
8134 if (this->toplevel_decl_
!= NULL
)
8136 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
8137 bvar_decl
= this->toplevel_decl_
->temporary_statement()
8138 ->get_backend_variable(&context
);
8140 bvar
= backend
->local_variable(bfunction
, n
, btype
,
8145 this->backend_
= bvar
;
8148 return this->backend_
;
8151 // Class Result_variable.
8153 // Convert a result variable to the backend representation.
8156 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
8157 const std::string
& name
)
8159 if (this->backend_
== NULL
)
8161 Backend
* backend
= gogo
->backend();
8162 Type
* type
= this->type_
;
8163 if (type
->is_error())
8164 this->backend_
= backend
->error_variable();
8167 if (this->is_in_heap())
8168 type
= Type::make_pointer_type(type
);
8169 Btype
* btype
= type
->get_backend(gogo
);
8170 Bfunction
* bfunction
= function
->func_value()->get_decl();
8171 std::string n
= Gogo::unpack_hidden_name(name
);
8172 unsigned int flags
= 0;
8173 if (this->is_non_escaping_address_taken_
8174 && !this->is_in_heap())
8175 flags
|= Backend::variable_address_is_taken
;
8176 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
8181 return this->backend_
;
8184 // Class Named_constant.
8186 // Set the type of a named constant. This is only used to set the
8187 // type to an error type.
8190 Named_constant::set_type(Type
* t
)
8192 go_assert(this->type_
== NULL
|| t
->is_error_type());
8196 // Traverse the initializer expression.
8199 Named_constant::traverse_expression(Traverse
* traverse
)
8201 return Expression::traverse(&this->expr_
, traverse
);
8204 // Determine the type of the constant.
8207 Named_constant::determine_type()
8209 if (this->type_
!= NULL
)
8211 Type_context
context(this->type_
, false);
8212 this->expr_
->determine_type(&context
);
8216 // A constant may have an abstract type.
8217 Type_context
context(NULL
, true);
8218 this->expr_
->determine_type(&context
);
8219 this->type_
= this->expr_
->type();
8220 go_assert(this->type_
!= NULL
);
8224 // Indicate that we found and reported an error for this constant.
8227 Named_constant::set_error()
8229 this->type_
= Type::make_error_type();
8230 this->expr_
= Expression::make_error(this->location_
);
8233 // Export a constant.
8236 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
8238 exp
->write_c_string("const ");
8239 exp
->write_string(name
);
8240 exp
->write_c_string(" ");
8241 if (!this->type_
->is_abstract())
8243 exp
->write_type(this->type_
);
8244 exp
->write_c_string(" ");
8246 exp
->write_c_string("= ");
8248 Export_function_body
efb(exp
, 0);
8249 if (!this->type_
->is_abstract())
8250 efb
.set_type_context(this->type_
);
8251 this->expr()->export_expression(&efb
);
8252 exp
->write_string(efb
.body());
8254 exp
->write_c_string("\n");
8257 // Import a constant.
8260 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
8263 imp
->require_c_string("const ");
8264 *pname
= imp
->read_identifier();
8265 imp
->require_c_string(" ");
8266 if (imp
->peek_char() == '=')
8270 *ptype
= imp
->read_type();
8271 imp
->require_c_string(" ");
8273 imp
->require_c_string("= ");
8274 *pexpr
= Expression::import_expression(imp
, imp
->location());
8275 imp
->require_semicolon_if_old_version();
8276 imp
->require_c_string("\n");
8279 // Get the backend representation.
8282 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
8284 if (this->bconst_
== NULL
)
8286 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
8287 Type
* type
= this->type();
8288 Location loc
= this->location();
8290 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
8291 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
8292 if (type
!= NULL
&& type
->is_numeric_type())
8294 Btype
* btype
= type
->get_backend(gogo
);
8296 if (const_no
->package() == NULL
)
8297 name
= gogo
->pkgpath();
8299 name
= const_no
->package()->pkgpath();
8300 name
.push_back('.');
8301 name
.append(Gogo::unpack_hidden_name(const_no
->name()));
8303 gogo
->backend()->named_constant_expression(btype
, name
,
8306 this->bconst_
= const_decl
;
8308 return this->bconst_
;
8314 Type_declaration::add_method(const std::string
& name
, Function
* function
)
8316 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
8317 this->methods_
.push_back(ret
);
8321 // Add a method declaration.
8324 Type_declaration::add_method_declaration(const std::string
& name
,
8326 Function_type
* type
,
8329 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
8331 this->methods_
.push_back(ret
);
8335 // Return whether any methods are defined.
8338 Type_declaration::has_methods() const
8340 return !this->methods_
.empty();
8343 // Define methods for the real type.
8346 Type_declaration::define_methods(Named_type
* nt
)
8348 if (this->methods_
.empty())
8351 while (nt
->is_alias())
8353 Type
*t
= nt
->real_type()->forwarded();
8354 if (t
->named_type() != NULL
)
8355 nt
= t
->named_type();
8356 else if (t
->forward_declaration_type() != NULL
)
8358 Named_object
* no
= t
->forward_declaration_type()->named_object();
8359 Type_declaration
* td
= no
->type_declaration_value();
8360 td
->methods_
.insert(td
->methods_
.end(), this->methods_
.begin(),
8361 this->methods_
.end());
8362 this->methods_
.clear();
8367 for (std::vector
<Named_object
*>::const_iterator p
=
8368 this->methods_
.begin();
8369 p
!= this->methods_
.end();
8371 go_error_at((*p
)->location(),
8372 ("invalid receiver type "
8373 "(receiver must be a named type)"));
8378 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
8379 p
!= this->methods_
.end();
8382 if ((*p
)->is_function_declaration()
8383 || !(*p
)->func_value()->is_sink())
8384 nt
->add_existing_method(*p
);
8388 // We are using the type. Return true if we should issue a warning.
8391 Type_declaration::using_type()
8393 bool ret
= !this->issued_warning_
;
8394 this->issued_warning_
= true;
8398 // Class Unknown_name.
8400 // Set the real named object.
8403 Unknown_name::set_real_named_object(Named_object
* no
)
8405 go_assert(this->real_named_object_
== NULL
);
8406 go_assert(!no
->is_unknown());
8407 this->real_named_object_
= no
;
8410 // Class Named_object.
8412 Named_object::Named_object(const std::string
& name
,
8413 const Package
* package
,
8414 Classification classification
)
8415 : name_(name
), package_(package
), classification_(classification
),
8416 is_redefinition_(false)
8418 if (Gogo::is_sink_name(name
))
8419 go_assert(classification
== NAMED_OBJECT_SINK
);
8422 // Make an unknown name. This is used by the parser. The name must
8423 // be resolved later. Unknown names are only added in the current
8427 Named_object::make_unknown_name(const std::string
& name
,
8430 Named_object
* named_object
= new Named_object(name
, NULL
,
8431 NAMED_OBJECT_UNKNOWN
);
8432 Unknown_name
* value
= new Unknown_name(location
);
8433 named_object
->u_
.unknown_value
= value
;
8434 return named_object
;
8440 Named_object::make_constant(const Typed_identifier
& tid
,
8441 const Package
* package
, Expression
* expr
,
8444 Named_object
* named_object
= new Named_object(tid
.name(), package
,
8445 NAMED_OBJECT_CONST
);
8446 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
8449 named_object
->u_
.const_value
= named_constant
;
8450 return named_object
;
8453 // Make a named type.
8456 Named_object::make_type(const std::string
& name
, const Package
* package
,
8457 Type
* type
, Location location
)
8459 Named_object
* named_object
= new Named_object(name
, package
,
8461 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
8462 named_object
->u_
.type_value
= named_type
;
8463 return named_object
;
8466 // Make a type declaration.
8469 Named_object::make_type_declaration(const std::string
& name
,
8470 const Package
* package
,
8473 Named_object
* named_object
= new Named_object(name
, package
,
8474 NAMED_OBJECT_TYPE_DECLARATION
);
8475 Type_declaration
* type_declaration
= new Type_declaration(location
);
8476 named_object
->u_
.type_declaration
= type_declaration
;
8477 return named_object
;
8483 Named_object::make_variable(const std::string
& name
, const Package
* package
,
8486 Named_object
* named_object
= new Named_object(name
, package
,
8488 named_object
->u_
.var_value
= variable
;
8489 return named_object
;
8492 // Make a result variable.
8495 Named_object::make_result_variable(const std::string
& name
,
8496 Result_variable
* result
)
8498 Named_object
* named_object
= new Named_object(name
, NULL
,
8499 NAMED_OBJECT_RESULT_VAR
);
8500 named_object
->u_
.result_var_value
= result
;
8501 return named_object
;
8504 // Make a sink. This is used for the special blank identifier _.
8507 Named_object::make_sink()
8509 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
8512 // Make a named function.
8515 Named_object::make_function(const std::string
& name
, const Package
* package
,
8518 Named_object
* named_object
= new Named_object(name
, package
,
8520 named_object
->u_
.func_value
= function
;
8521 return named_object
;
8524 // Make a function declaration.
8527 Named_object::make_function_declaration(const std::string
& name
,
8528 const Package
* package
,
8529 Function_type
* fntype
,
8532 Named_object
* named_object
= new Named_object(name
, package
,
8533 NAMED_OBJECT_FUNC_DECLARATION
);
8534 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
8535 named_object
->u_
.func_declaration_value
= func_decl
;
8536 return named_object
;
8542 Named_object::make_package(const std::string
& alias
, Package
* package
)
8544 Named_object
* named_object
= new Named_object(alias
, NULL
,
8545 NAMED_OBJECT_PACKAGE
);
8546 named_object
->u_
.package_value
= package
;
8547 return named_object
;
8550 // Return the name to use in an error message.
8553 Named_object::message_name() const
8555 if (this->package_
== NULL
)
8556 return Gogo::message_name(this->name_
);
8558 if (this->package_
->has_package_name())
8559 ret
= this->package_
->package_name();
8561 ret
= this->package_
->pkgpath();
8562 ret
= Gogo::message_name(ret
);
8564 ret
+= Gogo::message_name(this->name_
);
8568 // Set the type when a declaration is defined.
8571 Named_object::set_type_value(Named_type
* named_type
)
8573 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
8574 Type_declaration
* td
= this->u_
.type_declaration
;
8575 td
->define_methods(named_type
);
8577 Named_object
* in_function
= td
->in_function(&index
);
8578 if (in_function
!= NULL
)
8579 named_type
->set_in_function(in_function
, index
);
8581 this->classification_
= NAMED_OBJECT_TYPE
;
8582 this->u_
.type_value
= named_type
;
8585 // Define a function which was previously declared.
8588 Named_object::set_function_value(Function
* function
)
8590 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
8591 if (this->func_declaration_value()->has_descriptor())
8593 Expression
* descriptor
=
8594 this->func_declaration_value()->descriptor(NULL
, NULL
);
8595 function
->set_descriptor(descriptor
);
8597 this->classification_
= NAMED_OBJECT_FUNC
;
8598 // FIXME: We should free the old value.
8599 this->u_
.func_value
= function
;
8602 // Declare an unknown object as a type declaration.
8605 Named_object::declare_as_type()
8607 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
8608 Unknown_name
* unk
= this->u_
.unknown_value
;
8609 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
8610 this->u_
.type_declaration
= new Type_declaration(unk
->location());
8614 // Return the location of a named object.
8617 Named_object::location() const
8619 switch (this->classification_
)
8622 case NAMED_OBJECT_UNINITIALIZED
:
8625 case NAMED_OBJECT_ERRONEOUS
:
8626 return Linemap::unknown_location();
8628 case NAMED_OBJECT_UNKNOWN
:
8629 return this->unknown_value()->location();
8631 case NAMED_OBJECT_CONST
:
8632 return this->const_value()->location();
8634 case NAMED_OBJECT_TYPE
:
8635 return this->type_value()->location();
8637 case NAMED_OBJECT_TYPE_DECLARATION
:
8638 return this->type_declaration_value()->location();
8640 case NAMED_OBJECT_VAR
:
8641 return this->var_value()->location();
8643 case NAMED_OBJECT_RESULT_VAR
:
8644 return this->result_var_value()->location();
8646 case NAMED_OBJECT_SINK
:
8649 case NAMED_OBJECT_FUNC
:
8650 return this->func_value()->location();
8652 case NAMED_OBJECT_FUNC_DECLARATION
:
8653 return this->func_declaration_value()->location();
8655 case NAMED_OBJECT_PACKAGE
:
8656 return this->package_value()->location();
8660 // Traverse a Named_object.
8663 Named_object::traverse(Traverse
* traverse
, bool is_global
)
8665 const unsigned int traverse_mask
= traverse
->traverse_mask();
8666 const unsigned int e_or_t
= (Traverse::traverse_expressions
8667 | Traverse::traverse_types
);
8668 const unsigned int e_or_t_or_s
= (e_or_t
8669 | Traverse::traverse_statements
);
8671 int t
= TRAVERSE_CONTINUE
;
8672 switch (this->classification_
)
8674 case Named_object::NAMED_OBJECT_CONST
:
8675 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
8676 t
= traverse
->constant(this, is_global
);
8677 if (t
== TRAVERSE_CONTINUE
8678 && (traverse_mask
& e_or_t
) != 0)
8680 Type
* tc
= this->const_value()->type();
8683 if (Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
8684 return TRAVERSE_EXIT
;
8686 t
= this->const_value()->traverse_expression(traverse
);
8690 case Named_object::NAMED_OBJECT_VAR
:
8691 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8692 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
8693 t
= traverse
->variable(this);
8694 if (t
== TRAVERSE_CONTINUE
8695 && (traverse_mask
& e_or_t
) != 0)
8697 if (this->is_result_variable() || this->var_value()->has_type())
8699 Type
* tv
= (this->is_variable()
8700 ? this->var_value()->type()
8701 : this->result_var_value()->type());
8704 if (Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
8705 return TRAVERSE_EXIT
;
8709 if (t
== TRAVERSE_CONTINUE
8710 && (traverse_mask
& e_or_t_or_s
) != 0
8711 && this->is_variable())
8712 t
= this->var_value()->traverse_expression(traverse
,
8716 case Named_object::NAMED_OBJECT_FUNC
:
8717 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
8718 t
= traverse
->function(this);
8719 if (t
== TRAVERSE_CONTINUE
8721 & (Traverse::traverse_variables
8722 | Traverse::traverse_constants
8723 | Traverse::traverse_functions
8724 | Traverse::traverse_blocks
8725 | Traverse::traverse_statements
8726 | Traverse::traverse_expressions
8727 | Traverse::traverse_types
)) != 0)
8728 t
= this->func_value()->traverse(traverse
);
8731 case Named_object::NAMED_OBJECT_TYPE
:
8732 if ((traverse_mask
& e_or_t
) != 0)
8733 t
= Type::traverse(this->type_value(), traverse
);
8736 case Named_object::NAMED_OBJECT_PACKAGE
:
8737 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8738 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8739 case Named_object::NAMED_OBJECT_UNKNOWN
:
8740 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8743 case Named_object::NAMED_OBJECT_SINK
:
8753 // Export a named object.
8756 Named_object::export_named_object(Export
* exp
) const
8758 switch (this->classification_
)
8761 case NAMED_OBJECT_UNINITIALIZED
:
8762 case NAMED_OBJECT_UNKNOWN
:
8765 case NAMED_OBJECT_ERRONEOUS
:
8768 case NAMED_OBJECT_CONST
:
8769 this->const_value()->export_const(exp
, this->name_
);
8772 case NAMED_OBJECT_TYPE
:
8773 // Types are handled by export::write_types.
8776 case NAMED_OBJECT_TYPE_DECLARATION
:
8777 go_error_at(this->type_declaration_value()->location(),
8778 "attempt to export %<%s%> which was declared but not defined",
8779 this->message_name().c_str());
8782 case NAMED_OBJECT_FUNC_DECLARATION
:
8783 this->func_declaration_value()->export_func(exp
, this);
8786 case NAMED_OBJECT_VAR
:
8787 this->var_value()->export_var(exp
, this);
8790 case NAMED_OBJECT_RESULT_VAR
:
8791 case NAMED_OBJECT_SINK
:
8794 case NAMED_OBJECT_FUNC
:
8795 this->func_value()->export_func(exp
, this);
8800 // Convert a variable to the backend representation.
8803 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
8805 if (this->classification_
== NAMED_OBJECT_VAR
)
8806 return this->var_value()->get_backend_variable(gogo
, function
,
8807 this->package_
, this->name_
);
8808 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
8809 return this->result_var_value()->get_backend_variable(gogo
, function
,
8816 debug_go_named_object(Named_object
* no
)
8820 std::cerr
<< "<null>";
8823 std::cerr
<< "'" << no
->name() << "': ";
8825 switch (no
->classification())
8827 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8828 tag
= "uninitialized";
8830 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8833 case Named_object::NAMED_OBJECT_UNKNOWN
:
8836 case Named_object::NAMED_OBJECT_CONST
:
8839 case Named_object::NAMED_OBJECT_TYPE
:
8842 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8845 case Named_object::NAMED_OBJECT_VAR
:
8848 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8851 case Named_object::NAMED_OBJECT_SINK
:
8854 case Named_object::NAMED_OBJECT_FUNC
:
8857 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8860 case Named_object::NAMED_OBJECT_PACKAGE
:
8864 tag
= "<unknown named object classification>";
8867 std::cerr
<< tag
<< "\n";
8870 // Get the backend representation for this named object.
8873 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
8874 std::vector
<Btype
*>& type_decls
,
8875 std::vector
<Bfunction
*>& func_decls
)
8877 // If this is a definition, avoid trying to get the backend
8878 // representation, as that can crash.
8879 if (this->is_redefinition_
)
8881 go_assert(saw_errors());
8885 switch (this->classification_
)
8887 case NAMED_OBJECT_CONST
:
8888 if (!Gogo::is_erroneous_name(this->name_
))
8889 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
8892 case NAMED_OBJECT_TYPE
:
8894 Named_type
* named_type
= this->u_
.type_value
;
8896 // No need to do anything for aliases-- whatever has to be done
8897 // can be done for the alias target.
8898 if (named_type
->is_alias())
8901 if (!Gogo::is_erroneous_name(this->name_
))
8902 type_decls
.push_back(named_type
->get_backend(gogo
));
8904 // We need to produce a type descriptor for every named
8905 // type, and for a pointer to every named type, since
8906 // other files or packages might refer to them. We need
8907 // to do this even for hidden types, because they might
8908 // still be returned by some function. Simply calling the
8909 // type_descriptor method is enough to create the type
8910 // descriptor, even though we don't do anything with it.
8911 if (this->package_
== NULL
&& !saw_errors())
8914 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8915 Type
* pn
= Type::make_pointer_type(named_type
);
8916 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8917 if (named_type
->in_heap())
8919 named_type
->gc_symbol_pointer(gogo
);
8920 pn
->gc_symbol_pointer(gogo
);
8926 case NAMED_OBJECT_TYPE_DECLARATION
:
8927 go_error_at(Linemap::unknown_location(),
8928 "reference to undefined type %qs",
8929 this->message_name().c_str());
8932 case NAMED_OBJECT_VAR
:
8933 case NAMED_OBJECT_RESULT_VAR
:
8934 case NAMED_OBJECT_SINK
:
8937 case NAMED_OBJECT_FUNC
:
8939 Function
* func
= this->u_
.func_value
;
8940 if (!Gogo::is_erroneous_name(this->name_
))
8941 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
8943 if (func
->block() != NULL
)
8944 func
->build(gogo
, this);
8948 case NAMED_OBJECT_ERRONEOUS
:
8958 Bindings::Bindings(Bindings
* enclosing
)
8959 : enclosing_(enclosing
), named_objects_(), bindings_()
8966 Bindings::clear_file_scope(Gogo
* gogo
)
8968 Contour::iterator p
= this->bindings_
.begin();
8969 while (p
!= this->bindings_
.end())
8972 if (p
->second
->package() != NULL
)
8974 else if (p
->second
->is_package())
8976 else if (p
->second
->is_function()
8977 && !p
->second
->func_value()->type()->is_method()
8978 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
8987 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
8988 p
= this->bindings_
.erase(p
);
8993 // Look up a symbol.
8996 Bindings::lookup(const std::string
& name
) const
8998 Contour::const_iterator p
= this->bindings_
.find(name
);
8999 if (p
!= this->bindings_
.end())
9000 return p
->second
->resolve();
9001 else if (this->enclosing_
!= NULL
)
9002 return this->enclosing_
->lookup(name
);
9007 // Look up a symbol locally.
9010 Bindings::lookup_local(const std::string
& name
) const
9012 Contour::const_iterator p
= this->bindings_
.find(name
);
9013 if (p
== this->bindings_
.end())
9018 // Remove an object from a set of bindings. This is used for a
9019 // special case in thunks for functions which call recover.
9022 Bindings::remove_binding(Named_object
* no
)
9024 Contour::iterator pb
= this->bindings_
.find(no
->name());
9025 go_assert(pb
!= this->bindings_
.end());
9026 this->bindings_
.erase(pb
);
9027 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
9028 pn
!= this->named_objects_
.end();
9033 this->named_objects_
.erase(pn
);
9040 // Add a method to the list of objects. This is not added to the
9041 // lookup table. This is so that we have a single list of objects
9042 // declared at the top level, which we walk through when it's time to
9043 // convert to trees.
9046 Bindings::add_method(Named_object
* method
)
9048 this->named_objects_
.push_back(method
);
9051 // Add a generic Named_object to a Contour.
9054 Bindings::add_named_object_to_contour(Contour
* contour
,
9055 Named_object
* named_object
)
9057 go_assert(named_object
== named_object
->resolve());
9058 const std::string
& name(named_object
->name());
9059 go_assert(!Gogo::is_sink_name(name
));
9061 std::pair
<Contour::iterator
, bool> ins
=
9062 contour
->insert(std::make_pair(name
, named_object
));
9065 // The name was already there.
9066 if (named_object
->package() != NULL
9067 && ins
.first
->second
->package() == named_object
->package()
9068 && (ins
.first
->second
->classification()
9069 == named_object
->classification()))
9071 // This is a second import of the same object.
9072 return ins
.first
->second
;
9074 ins
.first
->second
= this->new_definition(ins
.first
->second
,
9076 return ins
.first
->second
;
9080 // Don't push declarations on the list. We push them on when
9081 // and if we find the definitions. That way we genericize the
9082 // functions in order.
9083 if (!named_object
->is_type_declaration()
9084 && !named_object
->is_function_declaration()
9085 && !named_object
->is_unknown())
9086 this->named_objects_
.push_back(named_object
);
9087 return named_object
;
9091 // We had an existing named object OLD_OBJECT, and we've seen a new
9092 // one NEW_OBJECT with the same name. FIXME: This does not free the
9093 // new object when we don't need it.
9096 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
9098 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
9102 switch (old_object
->classification())
9105 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
9108 case Named_object::NAMED_OBJECT_ERRONEOUS
:
9111 case Named_object::NAMED_OBJECT_UNKNOWN
:
9113 Named_object
* real
= old_object
->unknown_value()->real_named_object();
9115 return this->new_definition(real
, new_object
);
9116 go_assert(!new_object
->is_unknown());
9117 old_object
->unknown_value()->set_real_named_object(new_object
);
9118 if (!new_object
->is_type_declaration()
9119 && !new_object
->is_function_declaration())
9120 this->named_objects_
.push_back(new_object
);
9124 case Named_object::NAMED_OBJECT_CONST
:
9127 case Named_object::NAMED_OBJECT_TYPE
:
9128 if (new_object
->is_type_declaration())
9132 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
9133 if (new_object
->is_type_declaration())
9135 if (new_object
->is_type())
9137 old_object
->set_type_value(new_object
->type_value());
9138 new_object
->type_value()->set_named_object(old_object
);
9139 this->named_objects_
.push_back(old_object
);
9144 case Named_object::NAMED_OBJECT_VAR
:
9145 case Named_object::NAMED_OBJECT_RESULT_VAR
:
9146 // We have already given an error in the parser for cases where
9147 // one parameter or result variable redeclares another one.
9148 if ((new_object
->is_variable()
9149 && new_object
->var_value()->is_parameter())
9150 || new_object
->is_result_variable())
9154 case Named_object::NAMED_OBJECT_SINK
:
9157 case Named_object::NAMED_OBJECT_FUNC
:
9160 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
9162 // We declare the hash and equality functions before defining
9163 // them, because we sometimes see that we need the declaration
9164 // while we are in the middle of a different function.
9166 // We declare the main function before the user defines it, to
9167 // give better error messages.
9169 // We declare inline functions before we define them, as we
9170 // only define them if we need them.
9171 if (new_object
->is_function()
9172 && ((Linemap::is_predeclared_location(old_object
->location())
9173 && Linemap::is_predeclared_location(new_object
->location()))
9174 || (Gogo::unpack_hidden_name(old_object
->name()) == "main"
9175 && Linemap::is_unknown_location(old_object
->location()))
9176 || (new_object
->package() != NULL
9177 && old_object
->func_declaration_value()->has_imported_body()
9178 && new_object
->func_value()->is_inline_only())))
9180 Function_type
* old_type
=
9181 old_object
->func_declaration_value()->type();
9182 Function_type
* new_type
= new_object
->func_value()->type();
9183 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
9185 Function_declaration
* fd
=
9186 old_object
->func_declaration_value();
9187 go_assert(fd
->asm_name().empty());
9188 old_object
->set_function_value(new_object
->func_value());
9189 this->named_objects_
.push_back(old_object
);
9196 case Named_object::NAMED_OBJECT_PACKAGE
:
9200 std::string n
= old_object
->message_name();
9202 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
9204 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
9206 old_object
->set_is_redefinition();
9207 new_object
->set_is_redefinition();
9209 if (!Linemap::is_unknown_location(old_object
->location())
9210 && !Linemap::is_predeclared_location(old_object
->location()))
9211 go_inform(old_object
->location(), "previous definition of %qs was here",
9217 // Add a named type.
9220 Bindings::add_named_type(Named_type
* named_type
)
9222 return this->add_named_object(named_type
->named_object());
9228 Bindings::add_function(const std::string
& name
, const Package
* package
,
9231 return this->add_named_object(Named_object::make_function(name
, package
,
9235 // Add a function declaration.
9238 Bindings::add_function_declaration(const std::string
& name
,
9239 const Package
* package
,
9240 Function_type
* type
,
9243 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
9245 return this->add_named_object(no
);
9248 // Define a type which was previously declared.
9251 Bindings::define_type(Named_object
* no
, Named_type
* type
)
9253 no
->set_type_value(type
);
9254 this->named_objects_
.push_back(no
);
9257 // Mark all local variables as used. This is used for some types of
9261 Bindings::mark_locals_used()
9263 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
9264 p
!= this->named_objects_
.end();
9266 if ((*p
)->is_variable())
9267 (*p
)->var_value()->set_is_used();
9270 // Traverse bindings.
9273 Bindings::traverse(Traverse
* traverse
, bool is_global
)
9275 unsigned int traverse_mask
= traverse
->traverse_mask();
9277 // We don't use an iterator because we permit the traversal to add
9278 // new global objects.
9279 const unsigned int e_or_t
= (Traverse::traverse_expressions
9280 | Traverse::traverse_types
);
9281 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9283 Named_object
* p
= this->named_objects_
[i
];
9284 if (p
->traverse(traverse
, is_global
) == TRAVERSE_EXIT
)
9285 return TRAVERSE_EXIT
;
9288 // If we need to traverse types, check the function declarations,
9289 // which have types. Also check any methods of a type declaration.
9290 if ((traverse_mask
& e_or_t
) != 0)
9292 for (Bindings::const_declarations_iterator p
=
9293 this->begin_declarations();
9294 p
!= this->end_declarations();
9297 if (p
->second
->is_function_declaration())
9299 if (Type::traverse(p
->second
->func_declaration_value()->type(),
9302 return TRAVERSE_EXIT
;
9304 else if (p
->second
->is_type_declaration())
9306 const std::vector
<Named_object
*>* methods
=
9307 p
->second
->type_declaration_value()->methods();
9308 for (std::vector
<Named_object
*>::const_iterator pm
=
9310 pm
!= methods
->end();
9313 Named_object
* no
= *pm
;
9315 if (no
->is_function())
9316 t
= no
->func_value()->type();
9317 else if (no
->is_function_declaration())
9318 t
= no
->func_declaration_value()->type();
9321 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
9322 return TRAVERSE_EXIT
;
9328 // Traverse function declarations when needed.
9329 if ((traverse_mask
& Traverse::traverse_func_declarations
) != 0)
9331 for (Bindings::const_declarations_iterator p
= this->begin_declarations();
9332 p
!= this->end_declarations();
9335 if (p
->second
->is_function_declaration())
9337 if (traverse
->function_declaration(p
->second
) == TRAVERSE_EXIT
)
9338 return TRAVERSE_EXIT
;
9343 return TRAVERSE_CONTINUE
;
9347 Bindings::debug_dump()
9349 std::set
<Named_object
*> defs
;
9350 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9351 defs
.insert(this->named_objects_
[i
]);
9352 for (Contour::iterator p
= this->bindings_
.begin();
9353 p
!= this->bindings_
.end();
9356 const char* tag
= " ";
9357 if (defs
.find(p
->second
) != defs
.end())
9360 debug_go_named_object(p
->second
);
9365 debug_go_bindings(Bindings
* bindings
)
9367 if (bindings
!= NULL
)
9368 bindings
->debug_dump();
9373 // Clear any references to this label.
9378 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
9379 p
!= this->refs_
.end();
9382 this->refs_
.clear();
9385 // Get the backend representation for a label.
9388 Label::get_backend_label(Translate_context
* context
)
9390 if (this->blabel_
== NULL
)
9392 Function
* function
= context
->function()->func_value();
9393 Bfunction
* bfunction
= function
->get_decl();
9394 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
9397 return this->blabel_
;
9400 // Return an expression for the address of this label.
9403 Label::get_addr(Translate_context
* context
, Location location
)
9405 Blabel
* label
= this->get_backend_label(context
);
9406 return context
->backend()->label_address(label
, location
);
9409 // Return the dummy label that represents any instance of the blank label.
9412 Label::create_dummy_label()
9414 static Label
* dummy_label
;
9415 if (dummy_label
== NULL
)
9417 dummy_label
= new Label("_");
9418 dummy_label
->set_is_used();
9423 // Class Unnamed_label.
9425 // Get the backend representation for an unnamed label.
9428 Unnamed_label::get_blabel(Translate_context
* context
)
9430 if (this->blabel_
== NULL
)
9432 Function
* function
= context
->function()->func_value();
9433 Bfunction
* bfunction
= function
->get_decl();
9434 this->blabel_
= context
->backend()->label(bfunction
, "",
9437 return this->blabel_
;
9440 // Return a statement which defines this unnamed label.
9443 Unnamed_label::get_definition(Translate_context
* context
)
9445 Blabel
* blabel
= this->get_blabel(context
);
9446 return context
->backend()->label_definition_statement(blabel
);
9449 // Return a goto statement to this unnamed label.
9452 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
9454 Blabel
* blabel
= this->get_blabel(context
);
9455 return context
->backend()->goto_statement(blabel
, location
);
9460 Package::Package(const std::string
& pkgpath
,
9461 const std::string
& pkgpath_symbol
, Location location
)
9462 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
9463 package_name_(), bindings_(new Bindings(NULL
)),
9466 go_assert(!pkgpath
.empty());
9469 // Set the package name.
9472 Package::set_package_name(const std::string
& package_name
, Location location
)
9474 go_assert(!package_name
.empty());
9475 if (this->package_name_
.empty())
9476 this->package_name_
= package_name
;
9477 else if (this->package_name_
!= package_name
)
9478 go_error_at(location
,
9479 ("saw two different packages with "
9480 "the same package path %s: %s, %s"),
9481 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
9482 package_name
.c_str());
9485 // Return the pkgpath symbol, which is a prefix for symbols defined in
9489 Package::pkgpath_symbol() const
9491 if (this->pkgpath_symbol_
.empty())
9492 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
9493 return this->pkgpath_symbol_
;
9496 // Set the package path symbol.
9499 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
9501 go_assert(!pkgpath_symbol
.empty());
9502 if (this->pkgpath_symbol_
.empty())
9503 this->pkgpath_symbol_
= pkgpath_symbol
;
9505 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
9508 // Note that symbol from this package was and qualified by ALIAS.
9511 Package::note_usage(const std::string
& alias
) const
9513 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9514 go_assert(p
!= this->aliases_
.end());
9515 p
->second
->note_usage();
9518 // Forget a given usage. If forgetting this usage means this package becomes
9519 // unused, report that error.
9522 Package::forget_usage(Expression
* usage
) const
9524 if (this->fake_uses_
.empty())
9527 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
9528 go_assert(p
!= this->fake_uses_
.end());
9529 this->fake_uses_
.erase(p
);
9531 if (this->fake_uses_
.empty())
9532 go_error_at(this->location(), "imported and not used: %s",
9533 Gogo::message_name(this->package_name()).c_str());
9536 // Clear the used field for the next file. If the only usages of this package
9537 // are possibly fake, keep the fake usages for lowering.
9540 Package::clear_used()
9542 std::string dot_alias
= "." + this->package_name();
9543 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
9544 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
9545 this->fake_uses_
.clear();
9547 this->aliases_
.clear();
9551 Package::add_alias(const std::string
& alias
, Location location
)
9553 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9554 if (p
== this->aliases_
.end())
9556 std::pair
<Aliases::iterator
, bool> ret
;
9557 ret
= this->aliases_
.insert(std::make_pair(alias
,
9558 new Package_alias(location
)));
9564 // Determine types of constants. Everything else in a package
9565 // (variables, function declarations) should already have a fixed
9566 // type. Constants may have abstract types.
9569 Package::determine_types()
9571 Bindings
* bindings
= this->bindings_
;
9572 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
9573 p
!= bindings
->end_definitions();
9576 if ((*p
)->is_const())
9577 (*p
)->const_value()->determine_type();
9585 Traverse::~Traverse()
9587 if (this->types_seen_
!= NULL
)
9588 delete this->types_seen_
;
9589 if (this->expressions_seen_
!= NULL
)
9590 delete this->expressions_seen_
;
9593 // Record that we are looking at a type, and return true if we have
9597 Traverse::remember_type(const Type
* type
)
9599 if (type
->is_error_type())
9601 go_assert((this->traverse_mask() & traverse_types
) != 0
9602 || (this->traverse_mask() & traverse_expressions
) != 0);
9603 // We mostly only have to remember named types. But it turns out
9604 // that an interface type can refer to itself without using a name
9605 // by relying on interface inheritance, as in
9607 // type I interface { F() interface{I} }
9609 // Similarly it is possible for array types to refer to themselves
9610 // without a name, e.g.
9612 // var x [uintptr(unsafe.Sizeof(&x))]byte
9614 if (type
->classification() != Type::TYPE_NAMED
9615 && type
->classification() != Type::TYPE_ARRAY
9616 && type
->classification() != Type::TYPE_INTERFACE
)
9618 if (this->types_seen_
== NULL
)
9619 this->types_seen_
= new Types_seen();
9620 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
9624 // Record that we are looking at an expression, and return true if we
9625 // have already seen it. NB: this routine used to assert if the traverse
9626 // mask did not include expressions/types -- this is no longer the case,
9627 // since it can be useful to remember specific expressions during
9628 // walks that only cover statements.
9631 Traverse::remember_expression(const Expression
* expression
)
9633 if (this->expressions_seen_
== NULL
)
9634 this->expressions_seen_
= new Expressions_seen();
9635 std::pair
<Expressions_seen::iterator
, bool> ins
=
9636 this->expressions_seen_
->insert(expression
);
9640 // The default versions of these functions should never be called: the
9641 // traversal mask indicates which functions may be called.
9644 Traverse::variable(Named_object
*)
9650 Traverse::constant(Named_object
*, bool)
9656 Traverse::function(Named_object
*)
9662 Traverse::block(Block
*)
9668 Traverse::statement(Block
*, size_t*, Statement
*)
9674 Traverse::expression(Expression
**)
9680 Traverse::type(Type
*)
9686 Traverse::function_declaration(Named_object
*)
9691 // Class Statement_inserter.
9694 Statement_inserter::insert(Statement
* s
)
9696 if (this->statements_added_
!= NULL
)
9697 this->statements_added_
->insert(s
);
9699 if (this->block_
!= NULL
)
9701 go_assert(this->pindex_
!= NULL
);
9702 this->block_
->insert_statement_before(*this->pindex_
, s
);
9705 else if (this->var_
!= NULL
)
9706 this->var_
->add_preinit_statement(this->gogo_
, s
);
9708 go_assert(saw_errors());