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),
50 pkgpath_from_option_(false),
51 prefix_from_option_(false),
52 relative_import_path_(),
54 check_divide_by_zero_(true),
55 check_divide_overflow_(true),
56 compiling_runtime_(false),
57 debug_escape_level_(0),
58 debug_optimization_(false),
59 nil_check_size_threshold_(4096),
62 specific_type_functions_(),
63 specific_type_functions_are_written_(false),
64 named_types_are_converted_(false),
68 imported_inlinable_functions_(),
69 imported_inline_functions_()
71 const Location loc
= Linemap::predeclared_location();
73 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
74 RUNTIME_TYPE_KIND_UINT8
);
75 this->add_named_type(uint8_type
);
76 this->add_named_type(Type::make_integer_type("uint16", true, 16,
77 RUNTIME_TYPE_KIND_UINT16
));
78 this->add_named_type(Type::make_integer_type("uint32", true, 32,
79 RUNTIME_TYPE_KIND_UINT32
));
80 this->add_named_type(Type::make_integer_type("uint64", true, 64,
81 RUNTIME_TYPE_KIND_UINT64
));
83 this->add_named_type(Type::make_integer_type("int8", false, 8,
84 RUNTIME_TYPE_KIND_INT8
));
85 this->add_named_type(Type::make_integer_type("int16", false, 16,
86 RUNTIME_TYPE_KIND_INT16
));
87 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
88 RUNTIME_TYPE_KIND_INT32
);
89 this->add_named_type(int32_type
);
90 this->add_named_type(Type::make_integer_type("int64", false, 64,
91 RUNTIME_TYPE_KIND_INT64
));
93 this->add_named_type(Type::make_float_type("float32", 32,
94 RUNTIME_TYPE_KIND_FLOAT32
));
95 this->add_named_type(Type::make_float_type("float64", 64,
96 RUNTIME_TYPE_KIND_FLOAT64
));
98 this->add_named_type(Type::make_complex_type("complex64", 64,
99 RUNTIME_TYPE_KIND_COMPLEX64
));
100 this->add_named_type(Type::make_complex_type("complex128", 128,
101 RUNTIME_TYPE_KIND_COMPLEX128
));
103 int int_type_size
= pointer_size
;
104 if (int_type_size
< 32)
106 this->add_named_type(Type::make_integer_type("uint", true,
108 RUNTIME_TYPE_KIND_UINT
));
109 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
110 RUNTIME_TYPE_KIND_INT
);
111 this->add_named_type(int_type
);
113 this->add_named_type(Type::make_integer_type("uintptr", true,
115 RUNTIME_TYPE_KIND_UINTPTR
));
117 // "byte" is an alias for "uint8".
118 uint8_type
->integer_type()->set_is_byte();
119 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
121 byte_type
->type_value()->set_is_alias();
122 this->add_named_type(byte_type
->type_value());
124 // "rune" is an alias for "int32".
125 int32_type
->integer_type()->set_is_rune();
126 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
128 rune_type
->type_value()->set_is_alias();
129 this->add_named_type(rune_type
->type_value());
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 this->globals_
->add_constant(Typed_identifier("true",
149 Type::make_boolean_type(),
152 Expression::make_boolean(true, loc
),
154 this->globals_
->add_constant(Typed_identifier("false",
155 Type::make_boolean_type(),
158 Expression::make_boolean(false, loc
),
161 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
164 Expression::make_nil(loc
),
167 Type
* abstract_int_type
= Type::make_abstract_integer_type();
168 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
171 Expression::make_iota(),
174 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
175 new_type
->set_is_varargs();
176 new_type
->set_is_builtin();
177 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
179 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
180 make_type
->set_is_varargs();
181 make_type
->set_is_builtin();
182 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
184 Typed_identifier_list
* len_result
= new Typed_identifier_list();
185 len_result
->push_back(Typed_identifier("", int_type
, loc
));
186 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
188 len_type
->set_is_builtin();
189 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
191 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
192 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
193 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
195 cap_type
->set_is_builtin();
196 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
198 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
199 print_type
->set_is_varargs();
200 print_type
->set_is_builtin();
201 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
203 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
204 print_type
->set_is_varargs();
205 print_type
->set_is_builtin();
206 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
208 Type
*empty
= Type::make_empty_interface_type(loc
);
209 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
210 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
211 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
213 panic_type
->set_is_builtin();
214 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
216 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
217 recover_result
->push_back(Typed_identifier("", empty
, loc
));
218 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
221 recover_type
->set_is_builtin();
222 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
224 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
225 close_type
->set_is_varargs();
226 close_type
->set_is_builtin();
227 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
229 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
230 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
231 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
233 copy_type
->set_is_varargs();
234 copy_type
->set_is_builtin();
235 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
237 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
238 append_type
->set_is_varargs();
239 append_type
->set_is_builtin();
240 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
242 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
243 complex_type
->set_is_varargs();
244 complex_type
->set_is_builtin();
245 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
247 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
248 real_type
->set_is_varargs();
249 real_type
->set_is_builtin();
250 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
252 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
253 imag_type
->set_is_varargs();
254 imag_type
->set_is_builtin();
255 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
257 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
258 delete_type
->set_is_varargs();
259 delete_type
->set_is_builtin();
260 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
264 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
266 go_assert(!pkgpath
.empty());
267 return go_encode_id(pkgpath
);
270 // Return a hash code for a string, given a starting hash.
273 Gogo::hash_string(const std::string
& s
, unsigned int h
)
275 const char* p
= s
.data();
276 size_t len
= s
.length();
277 for (; len
> 0; --len
)
285 // Get the package path to use for type reflection data. This should
286 // ideally be unique across the entire link.
289 Gogo::pkgpath() const
291 go_assert(this->pkgpath_set_
);
292 return this->pkgpath_
;
295 // Set the package path from the -fgo-pkgpath command line option.
298 Gogo::set_pkgpath(const std::string
& arg
)
300 go_assert(!this->pkgpath_set_
);
301 this->pkgpath_
= go_mangle_pkgpath(arg
);
302 this->pkgpath_set_
= true;
303 this->pkgpath_from_option_
= true;
306 // Get the package path to use for symbol names.
309 Gogo::pkgpath_symbol() const
311 go_assert(this->pkgpath_set_
);
312 return this->pkgpath_symbol_
;
315 // Set the unique prefix to use to determine the package path, from
316 // the -fgo-prefix command line option.
319 Gogo::set_prefix(const std::string
& arg
)
321 go_assert(!this->prefix_from_option_
);
323 this->prefix_from_option_
= true;
326 // Given a name which may or may not have been hidden, append the
327 // appropriate version of the name to the result string. Take care
328 // to avoid creating a sequence that will be rejected by go_encode_id
329 // (avoid ..u, ..U, ..z).
331 Gogo::append_possibly_hidden_name(std::string
*result
, const std::string
& name
)
333 // FIXME: This adds in pkgpath twice for hidden symbols, which is
335 if (!Gogo::is_hidden_name(name
))
340 std::string pkgpath
= Gogo::hidden_name_pkgpath(name
);
341 char lastR
= result
->at(result
->length() - 1);
342 char firstP
= pkgpath
.at(0);
343 if (lastR
== '.' && (firstP
== 'u' || firstP
== 'U' || firstP
== 'z'))
347 n
.append(Gogo::unpack_hidden_name(name
));
352 // Munge name for use in an error message.
355 Gogo::message_name(const std::string
& name
)
357 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
360 // Get the package name.
363 Gogo::package_name() const
365 go_assert(this->package_
!= NULL
);
366 return this->package_
->package_name();
369 // Set the package name.
372 Gogo::set_package_name(const std::string
& package_name
,
375 if (this->package_
!= NULL
)
377 if (this->package_
->package_name() != package_name
)
378 go_error_at(location
, "expected package %<%s%>",
379 Gogo::message_name(this->package_
->package_name()).c_str());
383 // Now that we know the name of the package we are compiling, set
384 // the package path to use for reflect.Type.PkgPath and global
386 if (this->pkgpath_set_
)
387 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
390 if (!this->prefix_from_option_
&& package_name
== "main")
392 this->pkgpath_
= package_name
;
393 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
397 if (!this->prefix_from_option_
)
398 this->prefix_
= "go";
399 this->pkgpath_
= (go_mangle_pkgpath(this->prefix_
) + '.'
401 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
402 + Gogo::pkgpath_for_symbol(package_name
));
404 this->pkgpath_set_
= true;
407 this->package_
= this->register_package(this->pkgpath_
,
408 this->pkgpath_symbol_
, location
);
409 this->package_
->set_package_name(package_name
, location
);
411 if (this->is_main_package())
413 // Declare "main" as a function which takes no parameters and
415 Location uloc
= Linemap::unknown_location();
416 this->declare_function(Gogo::pack_hidden_name("main", false),
417 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
422 // Return whether this is the "main" package. This is not true if
423 // -fgo-pkgpath or -fgo-prefix was used.
426 Gogo::is_main_package() const
428 return (this->package_name() == "main"
429 && !this->pkgpath_from_option_
430 && !this->prefix_from_option_
);
436 Gogo::import_package(const std::string
& filename
,
437 const std::string
& local_name
,
438 bool is_local_name_exported
,
442 if (filename
.empty())
444 go_error_at(location
, "import path is empty");
448 const char *pf
= filename
.data();
449 const char *pend
= pf
+ filename
.length();
453 int adv
= Lex::fetch_char(pf
, &c
);
456 go_error_at(location
, "import path contains invalid UTF-8 sequence");
461 go_error_at(location
, "import path contains NUL");
464 if (c
< 0x20 || c
== 0x7f)
466 go_error_at(location
, "import path contains control character");
471 go_error_at(location
, "import path contains backslash; use slash");
474 if (Lex::is_unicode_space(c
))
476 go_error_at(location
, "import path contains space character");
479 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
481 go_error_at(location
,
482 "import path contains invalid character '%c'", c
);
488 if (IS_ABSOLUTE_PATH(filename
.c_str()))
490 go_error_at(location
, "import path cannot be absolute path");
494 if (local_name
== "init")
495 go_error_at(location
, "cannot import package as init");
497 if (filename
== "unsafe")
499 this->import_unsafe(local_name
, is_local_name_exported
, location
);
500 this->current_file_imported_unsafe_
= true;
504 Imports::const_iterator p
= this->imports_
.find(filename
);
505 if (p
!= this->imports_
.end())
507 Package
* package
= p
->second
;
508 package
->set_location(location
);
509 std::string ln
= local_name
;
510 bool is_ln_exported
= is_local_name_exported
;
513 ln
= package
->package_name();
514 go_assert(!ln
.empty());
515 is_ln_exported
= Lex::is_exported_name(ln
);
521 Bindings
* bindings
= package
->bindings();
522 for (Bindings::const_declarations_iterator pd
=
523 bindings
->begin_declarations();
524 pd
!= bindings
->end_declarations();
526 this->add_dot_import_object(pd
->second
);
527 std::string dot_alias
= "." + package
->package_name();
528 package
->add_alias(dot_alias
, location
);
532 package
->add_alias(ln
, location
);
533 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
534 this->package_
->bindings()->add_package(ln
, package
);
539 Import::Stream
* stream
= Import::open_package(filename
, location
,
540 this->relative_import_path_
);
544 go_error_at(location
, "import file %qs not found", filename
.c_str());
548 Import
* imp
= new Import(stream
, location
);
549 imp
->register_builtin_types(this);
550 Package
* package
= imp
->import(this, local_name
, is_local_name_exported
);
553 if (package
->pkgpath() == this->pkgpath())
554 go_error_at(location
,
555 ("imported package uses same package path as package "
556 "being compiled (see %<-fgo-pkgpath%> option)"));
558 this->imports_
.insert(std::make_pair(filename
, package
));
564 // FIXME: we never delete imp; we may need it for inlinable functions.
568 Gogo::lookup_init(const std::string
& init_name
)
570 Import_init
tmp("", init_name
, -1);
571 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
572 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
575 // Add an import control function for an imported package to the list.
578 Gogo::add_import_init_fn(const std::string
& package_name
,
579 const std::string
& init_name
, int prio
)
581 for (Import_init_set::iterator p
=
582 this->imported_init_fns_
.begin();
583 p
!= this->imported_init_fns_
.end();
586 Import_init
*ii
= (*p
);
587 if (ii
->init_name() == init_name
)
589 // If a test of package P1, built as part of package P1,
590 // imports package P2, and P2 imports P1 (perhaps
591 // indirectly), then we will see the same import name with
592 // different import priorities. That is OK, so don't give
593 // an error about it.
594 if (ii
->package_name() != package_name
)
596 go_error_at(Linemap::unknown_location(),
597 "duplicate package initialization name %qs",
598 Gogo::message_name(init_name
).c_str());
599 go_inform(Linemap::unknown_location(), "used by package %qs",
600 Gogo::message_name(ii
->package_name()).c_str());
601 go_inform(Linemap::unknown_location(), " and by package %qs",
602 Gogo::message_name(package_name
).c_str());
604 ii
->set_priority(prio
);
609 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
610 this->imported_init_fns_
.insert(nii
);
613 // Return whether we are at the global binding level.
616 Gogo::in_global_scope() const
618 return this->functions_
.empty();
621 // Return the current binding contour.
624 Gogo::current_bindings()
626 if (!this->functions_
.empty())
627 return this->functions_
.back().blocks
.back()->bindings();
628 else if (this->package_
!= NULL
)
629 return this->package_
->bindings();
631 return this->globals_
;
635 Gogo::current_bindings() const
637 if (!this->functions_
.empty())
638 return this->functions_
.back().blocks
.back()->bindings();
639 else if (this->package_
!= NULL
)
640 return this->package_
->bindings();
642 return this->globals_
;
646 Gogo::update_init_priority(Import_init
* ii
,
647 std::set
<const Import_init
*>* visited
)
652 for (std::set
<std::string
>::const_iterator pci
=
653 ii
->precursors().begin();
654 pci
!= ii
->precursors().end();
657 Import_init
* succ
= this->lookup_init(*pci
);
658 if (visited
->find(succ
) == visited
->end())
659 update_init_priority(succ
, visited
);
660 succ_prior
= std::max(succ_prior
, succ
->priority());
662 if (ii
->priority() <= succ_prior
)
663 ii
->set_priority(succ_prior
+ 1);
667 Gogo::recompute_init_priorities()
669 std::set
<Import_init
*> nonroots
;
671 for (Import_init_set::const_iterator p
=
672 this->imported_init_fns_
.begin();
673 p
!= this->imported_init_fns_
.end();
676 const Import_init
*ii
= *p
;
677 for (std::set
<std::string
>::const_iterator pci
=
678 ii
->precursors().begin();
679 pci
!= ii
->precursors().end();
682 Import_init
* ii_init
= this->lookup_init(*pci
);
683 nonroots
.insert(ii_init
);
687 // Recursively update priorities starting at roots.
688 std::set
<const Import_init
*> visited
;
689 for (Import_init_set::iterator p
=
690 this->imported_init_fns_
.begin();
691 p
!= this->imported_init_fns_
.end();
694 Import_init
* ii
= *p
;
695 if (nonroots
.find(ii
) != nonroots
.end())
697 update_init_priority(ii
, &visited
);
701 // Add statements to INIT_STMTS which run the initialization
702 // functions for imported packages. This is only used for the "main"
706 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
, Bfunction
*bfunction
)
708 go_assert(this->is_main_package());
710 if (this->imported_init_fns_
.empty())
713 Location unknown_loc
= Linemap::unknown_location();
714 Function_type
* func_type
=
715 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
716 Btype
* fntype
= func_type
->get_backend_fntype(this);
718 // Recompute init priorities based on a walk of the init graph.
719 recompute_init_priorities();
721 // We must call them in increasing priority order.
722 std::vector
<const Import_init
*> v
;
723 for (Import_init_set::const_iterator p
=
724 this->imported_init_fns_
.begin();
725 p
!= this->imported_init_fns_
.end();
728 // Don't include dummy inits. They are not real functions.
729 if ((*p
)->is_dummy())
731 if ((*p
)->priority() < 0)
732 go_error_at(Linemap::unknown_location(),
733 "internal error: failed to set init priority for %s",
734 (*p
)->package_name().c_str());
737 std::sort(v
.begin(), v
.end(), priority_compare
);
739 // We build calls to the init functions, which take no arguments.
740 std::vector
<Bexpression
*> empty_args
;
741 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
745 const Import_init
* ii
= *p
;
746 std::string user_name
= ii
->package_name() + ".init";
747 const std::string
& init_name(ii
->init_name());
748 const unsigned int flags
=
749 (Backend::function_is_visible
750 | Backend::function_is_declaration
751 | Backend::function_is_inlinable
);
752 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
754 Bexpression
* pfunc_code
=
755 this->backend()->function_code_expression(pfunc
, unknown_loc
);
756 Bexpression
* pfunc_call
=
757 this->backend()->call_expression(bfunction
, pfunc_code
, empty_args
,
759 init_stmts
.push_back(this->backend()->expression_statement(bfunction
,
764 // Register global variables with the garbage collector. We need to
765 // register all variables which can hold a pointer value. They become
766 // roots during the mark phase. We build a struct that is easy to
767 // hook into a list of roots.
769 // type gcRoot struct {
770 // decl unsafe.Pointer // Pointer to variable.
771 // size uintptr // Total size of variable.
772 // ptrdata uintptr // Length of variable's gcdata.
773 // gcdata *byte // Pointer mask.
776 // type gcRootList struct {
782 // The last entry in the roots array has a NULL decl field.
785 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
786 std::vector
<Bstatement
*>& init_stmts
,
789 if (var_gc
.empty() && this->gc_roots_
.empty())
792 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
793 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
794 Type
* byte_type
= this->lookup_global("byte")->type_value();
795 Type
* pointer_byte_type
= Type::make_pointer_type(byte_type
);
796 Struct_type
* root_type
=
797 Type::make_builtin_struct_type(4,
799 "size", uintptr_type
,
800 "ptrdata", uintptr_type
,
801 "gcdata", pointer_byte_type
);
803 Location builtin_loc
= Linemap::predeclared_location();
804 unsigned long roots_len
= var_gc
.size() + this->gc_roots_
.size();
805 Expression
* length
= Expression::make_integer_ul(roots_len
, NULL
,
807 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
808 root_array_type
->set_is_array_incomparable();
810 Type
* int_type
= Type::lookup_integer_type("int");
811 Struct_type
* root_list_type
=
812 Type::make_builtin_struct_type(3,
815 "roots", root_array_type
);
817 // Build an initializer for the roots array.
819 Expression_list
* roots_init
= new Expression_list();
821 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
825 Expression_list
* init
= new Expression_list();
827 Location no_loc
= (*p
)->location();
828 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
829 Expression
* decl_addr
=
830 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
831 decl_addr
->unary_expression()->set_does_not_escape();
832 decl_addr
= Expression::make_cast(pvt
, decl_addr
, no_loc
);
833 init
->push_back(decl_addr
);
836 Expression::make_type_info(decl
->type(),
837 Expression::TYPE_INFO_SIZE
);
838 init
->push_back(size
);
840 Expression
* ptrdata
=
841 Expression::make_type_info(decl
->type(),
842 Expression::TYPE_INFO_BACKEND_PTRDATA
);
843 init
->push_back(ptrdata
);
845 Expression
* gcdata
= Expression::make_ptrmask_symbol(decl
->type());
846 init
->push_back(gcdata
);
848 Expression
* root_ctor
=
849 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
850 roots_init
->push_back(root_ctor
);
853 for (std::vector
<Expression
*>::const_iterator p
= this->gc_roots_
.begin();
854 p
!= this->gc_roots_
.end();
857 Expression_list
*init
= new Expression_list();
859 Expression
* expr
= *p
;
860 Location eloc
= expr
->location();
861 init
->push_back(Expression::make_cast(pvt
, expr
, eloc
));
863 Type
* type
= expr
->type()->points_to();
864 go_assert(type
!= NULL
);
867 Expression::make_type_info(type
,
868 Expression::TYPE_INFO_SIZE
);
869 init
->push_back(size
);
871 Expression
* ptrdata
=
872 Expression::make_type_info(type
,
873 Expression::TYPE_INFO_BACKEND_PTRDATA
);
874 init
->push_back(ptrdata
);
876 Expression
* gcdata
= Expression::make_ptrmask_symbol(type
);
877 init
->push_back(gcdata
);
879 Expression
* root_ctor
=
880 Expression::make_struct_composite_literal(root_type
, init
, eloc
);
881 roots_init
->push_back(root_ctor
);
884 // Build a constructor for the struct.
886 Expression_list
* root_list_init
= new Expression_list();
887 root_list_init
->push_back(Expression::make_nil(builtin_loc
));
888 root_list_init
->push_back(Expression::make_integer_ul(roots_len
, int_type
,
891 Expression
* roots_ctor
=
892 Expression::make_array_composite_literal(root_array_type
, roots_init
,
894 root_list_init
->push_back(roots_ctor
);
896 Expression
* root_list_ctor
=
897 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
900 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
902 root_addr
->unary_expression()->set_is_gc_root();
903 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
904 builtin_loc
, 1, root_addr
);
906 Translate_context
context(this, NULL
, NULL
, NULL
);
907 Bexpression
* bcall
= register_roots
->get_backend(&context
);
908 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
, bcall
));
911 // Build the list of type descriptors defined in this package. This is to help
912 // the reflect package to find compiler-generated types.
914 // type typeDescriptorList struct {
916 // types [...]unsafe.Pointer
920 type_descriptor_list_type(unsigned long len
)
922 Location builtin_loc
= Linemap::predeclared_location();
923 Type
* int_type
= Type::lookup_integer_type("int");
924 Type
* ptr_type
= Type::make_pointer_type(Type::make_void_type());
925 // Avoid creating zero-length type.
926 unsigned long nelems
= (len
!= 0 ? len
: 1);
927 Expression
* len_expr
= Expression::make_integer_ul(nelems
, NULL
,
929 Array_type
* array_type
= Type::make_array_type(ptr_type
, len_expr
);
930 array_type
->set_is_array_incomparable();
931 Struct_type
* list_type
=
932 Type::make_builtin_struct_type(2, "count", int_type
,
933 "types", array_type
);
938 Gogo::build_type_descriptor_list()
940 // Create the list type
941 Location builtin_loc
= Linemap::predeclared_location();
942 unsigned long len
= this->type_descriptors_
.size();
943 Struct_type
* list_type
= type_descriptor_list_type(len
);
944 Btype
* bt
= list_type
->get_backend(this);
945 Btype
* bat
= list_type
->field(1)->type()->get_backend(this);
947 // Create the variable
948 std::string name
= this->type_descriptor_list_symbol(this->pkgpath_symbol());
949 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bt
,
953 // Build the initializer
954 std::vector
<unsigned long> indexes
;
955 std::vector
<Bexpression
*> vals
;
956 std::vector
<Type
*>::iterator p
= this->type_descriptors_
.begin();
957 for (unsigned long i
= 0; i
< len
; ++i
, ++p
)
959 Bexpression
* bexpr
= (*p
)->type_descriptor_pointer(this,
961 indexes
.push_back(i
);
962 vals
.push_back(bexpr
);
964 Bexpression
* barray
=
965 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
968 Translate_context
context(this, NULL
, NULL
, NULL
);
969 std::vector
<Bexpression
*> fields
;
970 Expression
* len_expr
= Expression::make_integer_ul(len
, NULL
,
972 fields
.push_back(len_expr
->get_backend(&context
));
973 fields
.push_back(barray
);
975 this->backend()->constructor_expression(bt
, fields
, builtin_loc
);
977 this->backend()->implicit_variable_set_init(bv
, name
, bt
, false,
981 // Register the type descriptors with the runtime. This is to help
982 // the reflect package to find compiler-generated types.
985 Gogo::register_type_descriptors(std::vector
<Bstatement
*>& init_stmts
,
988 // Create the list type
989 Location builtin_loc
= Linemap::predeclared_location();
990 Struct_type
* list_type
= type_descriptor_list_type(1);
991 Btype
* bt
= list_type
->get_backend(this);
993 // Collect type lists from transitive imports.
994 std::vector
<std::string
> list_names
;
995 for (Import_init_set::iterator it
= this->imported_init_fns_
.begin();
996 it
!= this->imported_init_fns_
.end();
999 std::string pkgpath
=
1000 this->pkgpath_from_init_fn_name((*it
)->init_name());
1001 list_names
.push_back(this->type_descriptor_list_symbol(pkgpath
));
1003 // Add the main package itself.
1004 list_names
.push_back(this->type_descriptor_list_symbol("main"));
1006 // Build a list of lists.
1007 std::vector
<unsigned long> indexes
;
1008 std::vector
<Bexpression
*> vals
;
1009 unsigned long i
= 0;
1010 for (std::vector
<std::string
>::iterator p
= list_names
.begin();
1011 p
!= list_names
.end();
1015 this->backend()->implicit_variable_reference(*p
, *p
, bt
);
1016 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
1017 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
1019 indexes
.push_back(i
);
1020 vals
.push_back(bexpr
);
1023 Expression
* len_expr
= Expression::make_integer_ul(i
, NULL
, builtin_loc
);
1024 Type
* list_ptr_type
= Type::make_pointer_type(list_type
);
1025 Type
* list_array_type
= Type::make_array_type(list_ptr_type
, len_expr
);
1026 Btype
* bat
= list_array_type
->get_backend(this);
1027 Bexpression
* barray
=
1028 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
1031 // Create a variable holding the list.
1032 std::string name
= this->typelists_symbol();
1033 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bat
,
1036 this->backend()->implicit_variable_set_init(bv
, name
, bat
, true, true,
1039 // Build the call in main package's init function.
1040 Translate_context
context(this, NULL
, NULL
, NULL
);
1041 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
1042 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
1043 Type
* array_ptr_type
= Type::make_pointer_type(list_array_type
);
1044 Expression
* expr
= Expression::make_backend(bexpr
, array_ptr_type
,
1046 expr
= Runtime::make_call(Runtime::REGISTER_TYPE_DESCRIPTORS
,
1047 builtin_loc
, 2, len_expr
->copy(), expr
);
1048 Bexpression
* bcall
= expr
->get_backend(&context
);
1049 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
,
1053 // Build the decl for the initialization function.
1056 Gogo::initialization_function_decl()
1058 std::string name
= this->get_init_fn_name();
1059 Location loc
= this->package_
->location();
1061 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
1062 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
1063 return Named_object::make_function(name
, NULL
, initfn
);
1066 // Create the magic initialization function. CODE_STMT is the
1067 // code that it needs to run.
1070 Gogo::create_initialization_function(Named_object
* initfn
,
1071 Bstatement
* code_stmt
)
1073 // Make sure that we thought we needed an initialization function,
1074 // as otherwise we will not have reported it in the export data.
1075 go_assert(this->is_main_package() || this->need_init_fn_
);
1078 initfn
= this->initialization_function_decl();
1080 // Bind the initialization function code to a block.
1081 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
1082 Location pkg_loc
= this->package_
->location();
1083 std::vector
<Bvariable
*> vars
;
1084 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
1086 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
1088 go_assert(saw_errors());
1094 // Given an expression, collect all the global variables defined in
1095 // this package that it references.
1097 class Find_vars
: public Traverse
1100 // The list of variables we accumulate.
1101 typedef Unordered_set(Named_object
*) Vars
;
1103 // A hash table we use to avoid looping. The index is a
1104 // Named_object* or a Temporary_statement*. We only look through
1105 // objects defined in this package.
1106 typedef Unordered_set(const void*) Seen_objects
;
1110 : Traverse(traverse_expressions
),
1111 vars_(), seen_objects_()
1114 // An iterator through the variables found, after the traversal.
1115 typedef Vars::const_iterator const_iterator
;
1119 { return this->vars_
.begin(); }
1123 { return this->vars_
.end(); }
1126 expression(Expression
**);
1129 // Accumulated variables.
1131 // Objects we have already seen.
1132 Seen_objects seen_objects_
;
1135 // Collect global variables referenced by EXPR. Look through function
1136 // calls and variable initializations.
1139 Find_vars::expression(Expression
** pexpr
)
1141 Expression
* e
= *pexpr
;
1143 Var_expression
* ve
= e
->var_expression();
1146 Named_object
* v
= ve
->named_object();
1147 if (!v
->is_variable() || v
->package() != NULL
)
1149 // This is a result parameter or a variable defined in a
1150 // different package. Either way we don't care about it.
1151 return TRAVERSE_CONTINUE
;
1154 std::pair
<Seen_objects::iterator
, bool> ins
=
1155 this->seen_objects_
.insert(v
);
1158 // We've seen this variable before.
1159 return TRAVERSE_CONTINUE
;
1162 if (v
->var_value()->is_global())
1163 this->vars_
.insert(v
);
1165 Expression
* init
= v
->var_value()->init();
1168 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1169 return TRAVERSE_EXIT
;
1173 // We traverse the code of any function or bound method we see. Note that
1174 // this means that we will traverse the code of a function or bound method
1175 // whose address is taken even if it is not called.
1176 Func_expression
* fe
= e
->func_expression();
1177 Bound_method_expression
* bme
= e
->bound_method_expression();
1178 if (fe
!= NULL
|| bme
!= NULL
)
1180 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1181 if (f
->is_function() && f
->package() == NULL
)
1183 std::pair
<Seen_objects::iterator
, bool> ins
=
1184 this->seen_objects_
.insert(f
);
1187 // This is the first time we have seen this name.
1188 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
1189 return TRAVERSE_EXIT
;
1194 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1197 Temporary_statement
* ts
= tre
->statement();
1198 Expression
* init
= ts
->init();
1201 std::pair
<Seen_objects::iterator
, bool> ins
=
1202 this->seen_objects_
.insert(ts
);
1205 // This is the first time we have seen this temporary
1207 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1208 return TRAVERSE_EXIT
;
1213 return TRAVERSE_CONTINUE
;
1216 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1219 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1222 Find_vars find_vars
;
1224 Expression::traverse(&expr
, &find_vars
);
1225 if (preinit
!= NULL
)
1226 preinit
->traverse(&find_vars
);
1229 Expression
* init
= dep
->var_value()->init();
1231 Expression::traverse(&init
, &find_vars
);
1232 if (dep
->var_value()->has_pre_init())
1233 dep
->var_value()->preinit()->traverse(&find_vars
);
1236 for (Find_vars::const_iterator p
= find_vars
.begin();
1237 p
!= find_vars
.end();
1246 // Sort variable initializations. If the initialization expression
1247 // for variable A refers directly or indirectly to the initialization
1248 // expression for variable B, then we must initialize B before A.
1254 : var_(NULL
), init_(NULL
), refs_(NULL
), dep_count_(0)
1257 Var_init(Named_object
* var
, Bstatement
* init
)
1258 : var_(var
), init_(init
), refs_(NULL
), dep_count_(0)
1261 // Return the variable.
1264 { return this->var_
; }
1266 // Return the initialization expression.
1269 { return this->init_
; }
1273 add_ref(Named_object
* var
);
1275 // The variables which this variable's initializers refer to.
1276 const std::vector
<Named_object
*>*
1278 { return this->refs_
; }
1280 // Clear the references, if any.
1284 // Return the number of remaining dependencies.
1287 { return this->dep_count_
; }
1289 // Increment the number of dependencies.
1292 { ++this->dep_count_
; }
1294 // Decrement the number of dependencies.
1297 { --this->dep_count_
; }
1300 // The variable being initialized.
1302 // The backend initialization statement.
1304 // Variables this refers to.
1305 std::vector
<Named_object
*>* refs_
;
1306 // The number of initializations this is dependent on. A variable
1307 // initialization should not be emitted if any of its dependencies
1308 // have not yet been resolved.
1315 Var_init::add_ref(Named_object
* var
)
1317 if (this->refs_
== NULL
)
1318 this->refs_
= new std::vector
<Named_object
*>;
1319 this->refs_
->push_back(var
);
1322 // Clear the references, if any.
1325 Var_init::clear_refs()
1327 if (this->refs_
!= NULL
)
1334 // For comparing Var_init keys in a map.
1337 operator<(const Var_init
& v1
, const Var_init
& v2
)
1338 { return v1
.var()->name() < v2
.var()->name(); }
1340 typedef std::list
<Var_init
> Var_inits
;
1342 // Sort the variable initializations. The rule we follow is that we
1343 // emit them in the order they appear in the array, except that if the
1344 // initialization expression for a variable V1 depends upon another
1345 // variable V2 then we initialize V1 after V2.
1348 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1350 if (var_inits
->empty())
1353 std::map
<Named_object
*, Var_init
*> var_to_init
;
1355 // A mapping from a variable initialization to a set of
1356 // variable initializations that depend on it.
1357 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1358 Init_deps init_deps
;
1359 bool init_loop
= false;
1361 // Compute all variable references.
1362 for (Var_inits::iterator pvar
= var_inits
->begin();
1363 pvar
!= var_inits
->end();
1366 Named_object
* var
= pvar
->var();
1367 var_to_init
[var
] = &*pvar
;
1369 Find_vars find_vars
;
1370 Expression
* init
= var
->var_value()->init();
1372 Expression::traverse(&init
, &find_vars
);
1373 if (var
->var_value()->has_pre_init())
1374 var
->var_value()->preinit()->traverse(&find_vars
);
1375 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1378 Expression
* dinit
= dep
->var_value()->init();
1380 Expression::traverse(&dinit
, &find_vars
);
1381 if (dep
->var_value()->has_pre_init())
1382 dep
->var_value()->preinit()->traverse(&find_vars
);
1384 for (Find_vars::const_iterator p
= find_vars
.begin();
1385 p
!= find_vars
.end();
1390 // Add dependencies to init_deps, and check for cycles.
1391 for (Var_inits::iterator pvar
= var_inits
->begin();
1392 pvar
!= var_inits
->end();
1395 Named_object
* var
= pvar
->var();
1397 const std::vector
<Named_object
*>* refs
= pvar
->refs();
1400 for (std::vector
<Named_object
*>::const_iterator pdep
= refs
->begin();
1401 pdep
!= refs
->end();
1404 Named_object
* dep
= *pdep
;
1407 // This is a reference from a variable to itself, which
1408 // may indicate a loop. We only report an error if
1409 // there is an initializer and there is no dependency.
1410 // When there is no initializer, it means that the
1411 // preinitializer sets the variable, which will appear
1412 // to be a loop here.
1413 if (var
->var_value()->init() != NULL
1414 && gogo
->var_depends_on(var
->var_value()) == NULL
)
1415 go_error_at(var
->location(),
1416 ("initialization expression for %qs "
1417 "depends upon itself"),
1418 var
->message_name().c_str());
1423 Var_init
* dep_init
= var_to_init
[dep
];
1424 if (dep_init
== NULL
)
1426 // This is a dependency on some variable that doesn't
1427 // have an initializer, so for purposes of
1428 // initialization ordering this is irrelevant.
1432 init_deps
[*dep_init
].insert(&(*pvar
));
1433 pvar
->add_dependency();
1435 // Check for cycles.
1436 const std::vector
<Named_object
*>* deprefs
= dep_init
->refs();
1437 if (deprefs
== NULL
)
1439 for (std::vector
<Named_object
*>::const_iterator pdepdep
=
1441 pdepdep
!= deprefs
->end();
1444 if (*pdepdep
== var
)
1446 go_error_at(var
->location(),
1447 ("initialization expressions for %qs and "
1448 "%qs depend upon each other"),
1449 var
->message_name().c_str(),
1450 dep
->message_name().c_str());
1451 go_inform(dep
->location(), "%qs defined here",
1452 dep
->message_name().c_str());
1460 var_to_init
.clear();
1461 for (Var_inits::iterator pvar
= var_inits
->begin();
1462 pvar
!= var_inits
->end();
1466 // If there are no dependencies then the declaration order is sorted.
1467 if (!init_deps
.empty() && !init_loop
)
1469 // Otherwise, sort variable initializations by emitting all variables with
1470 // no dependencies in declaration order. VAR_INITS is already in
1471 // declaration order.
1473 while (!var_inits
->empty())
1475 Var_inits::iterator v1
;;
1476 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1478 if (v1
->dep_count() == 0)
1481 go_assert(v1
!= var_inits
->end());
1483 // V1 either has no dependencies or its dependencies have already
1484 // been emitted, add it to READY next. When V1 is emitted, remove
1485 // a dependency from each V that depends on V1.
1486 ready
.splice(ready
.end(), *var_inits
, v1
);
1488 Init_deps::iterator p1
= init_deps
.find(*v1
);
1489 if (p1
!= init_deps
.end())
1491 std::set
<Var_init
*> resolved
= p1
->second
;
1492 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1493 pv
!= resolved
.end();
1495 (*pv
)->remove_dependency();
1496 init_deps
.erase(p1
);
1499 var_inits
->swap(ready
);
1500 go_assert(init_deps
.empty());
1504 // Give an error if the initialization expression for VAR depends on
1505 // itself. We only check if INIT is not NULL and there is no
1506 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1507 // which we will interpret as a loop.
1510 Gogo::check_self_dep(Named_object
* var
)
1512 Expression
* init
= var
->var_value()->init();
1513 Block
* preinit
= var
->var_value()->preinit();
1514 Named_object
* dep
= this->var_depends_on(var
->var_value());
1517 && expression_requires(init
, preinit
, NULL
, var
))
1518 go_error_at(var
->location(),
1519 "initialization expression for %qs depends upon itself",
1520 var
->message_name().c_str());
1523 // Write out the global definitions.
1526 Gogo::write_globals()
1528 this->build_interface_method_tables();
1530 Bindings
* bindings
= this->current_bindings();
1532 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1533 p
!= bindings
->end_declarations();
1536 // If any function declarations needed a descriptor, make sure
1538 Named_object
* no
= p
->second
;
1539 if (no
->is_function_declaration())
1540 no
->func_declaration_value()->build_backend_descriptor(this);
1543 // Lists of globally declared types, variables, constants, and functions
1544 // that must be defined.
1545 std::vector
<Btype
*> type_decls
;
1546 std::vector
<Bvariable
*> var_decls
;
1547 std::vector
<Bexpression
*> const_decls
;
1548 std::vector
<Bfunction
*> func_decls
;
1550 // The init function declaration and associated Bfunction, if necessary.
1551 Named_object
* init_fndecl
= NULL
;
1552 Bfunction
* init_bfn
= NULL
;
1554 std::vector
<Bstatement
*> init_stmts
;
1555 std::vector
<Bstatement
*> var_init_stmts
;
1557 if (this->is_main_package())
1559 init_fndecl
= this->initialization_function_decl();
1560 init_bfn
= init_fndecl
->func_value()->get_or_make_decl(this, init_fndecl
);
1563 // A list of variable initializations.
1564 Var_inits var_inits
;
1566 // A list of variables which need to be registered with the garbage
1568 size_t count_definitions
= bindings
->size_definitions();
1569 std::vector
<Named_object
*> var_gc
;
1570 var_gc
.reserve(count_definitions
);
1572 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1573 p
!= bindings
->end_definitions();
1576 Named_object
* no
= *p
;
1577 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1579 // There is nothing to do for a package.
1580 if (no
->is_package())
1583 // There is nothing to do for an object which was imported from
1584 // a different package into the global scope.
1585 if (no
->package() != NULL
)
1588 // Skip blank named functions and constants.
1589 if ((no
->is_function() && no
->func_value()->is_sink())
1590 || (no
->is_const() && no
->const_value()->is_sink()))
1593 // There is nothing useful we can output for constants which
1594 // have ideal or non-integral type.
1597 Type
* type
= no
->const_value()->type();
1599 type
= no
->const_value()->expr()->type();
1600 if (type
->is_abstract() || !type
->is_numeric_type())
1604 if (!no
->is_variable())
1605 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1608 Variable
* var
= no
->var_value();
1609 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1610 var_decls
.push_back(bvar
);
1612 // Check for a sink variable, which may be used to run an
1613 // initializer purely for its side effects.
1614 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1616 Bstatement
* var_init_stmt
= NULL
;
1617 if (!var
->has_pre_init())
1619 // If the backend representation of the variable initializer is
1620 // constant, we can just set the initial value using
1621 // global_var_set_init instead of during the init() function.
1622 // The initializer is constant if it is the zero-value of the
1623 // variable's type or if the initial value is an immutable value
1624 // that is not copied to the heap.
1625 bool is_static_initializer
= false;
1626 if (var
->init() == NULL
)
1627 is_static_initializer
= true;
1630 Type
* var_type
= var
->type();
1631 Expression
* init
= var
->init();
1632 Expression
* init_cast
=
1633 Expression::make_cast(var_type
, init
, var
->location());
1634 is_static_initializer
= init_cast
->is_static_initializer();
1637 // Non-constant variable initializations might need to create
1638 // temporary variables, which will need the initialization
1639 // function as context.
1640 Named_object
* var_init_fn
;
1641 if (is_static_initializer
)
1645 if (init_fndecl
== NULL
)
1647 init_fndecl
= this->initialization_function_decl();
1648 Function
* func
= init_fndecl
->func_value();
1649 init_bfn
= func
->get_or_make_decl(this, init_fndecl
);
1651 var_init_fn
= init_fndecl
;
1653 Bexpression
* var_binit
= var
->get_init(this, var_init_fn
);
1655 if (var_binit
== NULL
)
1657 else if (is_static_initializer
)
1659 if (expression_requires(var
->init(), NULL
,
1660 this->var_depends_on(var
), no
))
1661 go_error_at(no
->location(),
1662 "initialization expression for %qs depends "
1664 no
->message_name().c_str());
1665 this->backend()->global_variable_set_init(bvar
, var_binit
);
1669 this->backend()->expression_statement(init_bfn
, var_binit
);
1672 Location loc
= var
->location();
1673 Bexpression
* var_expr
=
1674 this->backend()->var_expression(bvar
, loc
);
1676 this->backend()->assignment_statement(init_bfn
, var_expr
,
1682 // We are going to create temporary variables which
1683 // means that we need an fndecl.
1684 if (init_fndecl
== NULL
)
1685 init_fndecl
= this->initialization_function_decl();
1687 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1688 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1691 if (var_init_stmt
!= NULL
)
1693 if (var
->init() == NULL
&& !var
->has_pre_init())
1694 var_init_stmts
.push_back(var_init_stmt
);
1696 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1698 else if (this->var_depends_on(var
) != NULL
)
1700 // This variable is initialized from something that is
1701 // not in its init or preinit. This variable needs to
1702 // participate in dependency analysis sorting, in case
1703 // some other variable depends on this one.
1704 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1705 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1706 Bstatement
* zero_stmt
=
1707 this->backend()->expression_statement(init_bfn
, zero
);
1708 var_inits
.push_back(Var_init(no
, zero_stmt
));
1711 // Collect a list of all global variables with pointers,
1712 // to register them for the garbage collector.
1713 if (!is_sink
&& var
->type()->has_pointer())
1715 // Avoid putting runtime.gcRoots itself on the list.
1716 if (this->compiling_runtime()
1717 && this->package_name() == "runtime"
1718 && (Gogo::unpack_hidden_name(no
->name()) == "gcRoots"
1719 || Gogo::unpack_hidden_name(no
->name()) == "gcRootsIndex"))
1722 var_gc
.push_back(no
);
1727 // Output inline functions, which are in different packages.
1728 for (std::vector
<Named_object
*>::const_iterator p
=
1729 this->imported_inline_functions_
.begin();
1730 p
!= this->imported_inline_functions_
.end();
1732 (*p
)->get_backend(this, const_decls
, type_decls
, func_decls
);
1734 // Build the list of type descriptors.
1735 this->build_type_descriptor_list();
1737 if (this->is_main_package())
1739 // Register the type descriptor lists, so that at run time
1740 // the reflect package can find compiler-created types, and
1741 // deduplicate if the same type is created with reflection.
1742 // This needs to be done before calling any package's init
1743 // function, as it may create type through reflection.
1744 this->register_type_descriptors(init_stmts
, init_bfn
);
1746 // Initialize imported packages.
1747 this->init_imports(init_stmts
, init_bfn
);
1750 // Register global variables with the garbage collector.
1751 this->register_gc_vars(var_gc
, init_stmts
, init_bfn
);
1753 // Simple variable initializations, after all variables are
1755 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1757 // Complete variable initializations, first sorting them into a
1759 if (!var_inits
.empty())
1761 sort_var_inits(this, &var_inits
);
1762 for (Var_inits::const_iterator p
= var_inits
.begin();
1763 p
!= var_inits
.end();
1765 init_stmts
.push_back(p
->init());
1768 // After all the variables are initialized, call the init
1769 // functions if there are any. Init functions take no arguments, so
1770 // we pass in EMPTY_ARGS to call them.
1771 std::vector
<Bexpression
*> empty_args
;
1772 for (std::vector
<Named_object
*>::const_iterator p
=
1773 this->init_functions_
.begin();
1774 p
!= this->init_functions_
.end();
1777 Location func_loc
= (*p
)->location();
1778 Function
* func
= (*p
)->func_value();
1779 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1780 Bexpression
* func_code
=
1781 this->backend()->function_code_expression(initfn
, func_loc
);
1782 Bexpression
* call
= this->backend()->call_expression(init_bfn
, func_code
,
1785 Bstatement
* ist
= this->backend()->expression_statement(init_bfn
, call
);
1786 init_stmts
.push_back(ist
);
1789 // Set up a magic function to do all the initialization actions.
1790 // This will be called if this package is imported.
1791 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1792 if (this->need_init_fn_
|| this->is_main_package())
1795 this->create_initialization_function(init_fndecl
, init_fncode
);
1796 if (init_fndecl
!= NULL
)
1797 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1800 // We should not have seen any new bindings created during the conversion.
1801 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1803 // Define all globally declared values.
1805 this->backend()->write_global_definitions(type_decls
, const_decls
,
1806 func_decls
, var_decls
);
1809 // Return the current block.
1812 Gogo::current_block()
1814 if (this->functions_
.empty())
1817 return this->functions_
.back().blocks
.back();
1820 // Look up a name in the current binding contour. If PFUNCTION is not
1821 // NULL, set it to the function in which the name is defined, or NULL
1822 // if the name is defined in global scope.
1825 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1827 if (pfunction
!= NULL
)
1830 if (Gogo::is_sink_name(name
))
1831 return Named_object::make_sink();
1833 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1834 p
!= this->functions_
.rend();
1837 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1840 if (pfunction
!= NULL
)
1841 *pfunction
= p
->function
;
1846 if (this->package_
!= NULL
)
1848 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1851 if (ret
->package() != NULL
)
1853 std::string dot_alias
= "." + ret
->package()->package_name();
1854 ret
->package()->note_usage(dot_alias
);
1860 // We do not look in the global namespace. If we did, the global
1861 // namespace would effectively hide names which were defined in
1862 // package scope which we have not yet seen. Instead,
1863 // define_global_names is called after parsing is over to connect
1864 // undefined names at package scope with names defined at global
1870 // Look up a name in the current block, without searching enclosing
1874 Gogo::lookup_in_block(const std::string
& name
) const
1876 go_assert(!this->functions_
.empty());
1877 go_assert(!this->functions_
.back().blocks
.empty());
1878 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1881 // Look up a name in the global namespace.
1884 Gogo::lookup_global(const char* name
) const
1886 return this->globals_
->lookup(name
);
1889 // Add an imported package.
1892 Gogo::add_imported_package(const std::string
& real_name
,
1893 const std::string
& alias_arg
,
1894 bool is_alias_exported
,
1895 const std::string
& pkgpath
,
1896 const std::string
& pkgpath_symbol
,
1898 bool* padd_to_globals
)
1900 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1901 ret
->set_package_name(real_name
, location
);
1903 *padd_to_globals
= false;
1905 if (alias_arg
== "_")
1907 else if (alias_arg
== ".")
1909 *padd_to_globals
= true;
1910 std::string dot_alias
= "." + real_name
;
1911 ret
->add_alias(dot_alias
, location
);
1915 std::string alias
= alias_arg
;
1919 is_alias_exported
= Lex::is_exported_name(alias
);
1921 ret
->add_alias(alias
, location
);
1922 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1923 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1924 if (!no
->is_package())
1931 // Register a package. This package may or may not be imported. This
1932 // returns the Package structure for the package, creating if it
1933 // necessary. LOCATION is the location of the import statement that
1934 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1935 // for names in the package; it may be the empty string, in which case
1936 // we either get it later or make a guess when we need it.
1939 Gogo::register_package(const std::string
& pkgpath
,
1940 const std::string
& pkgpath_symbol
, Location location
)
1942 Package
* package
= NULL
;
1943 std::pair
<Packages::iterator
, bool> ins
=
1944 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1947 // We have seen this package name before.
1948 package
= ins
.first
->second
;
1949 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1950 if (!pkgpath_symbol
.empty())
1951 package
->set_pkgpath_symbol(pkgpath_symbol
);
1952 if (Linemap::is_unknown_location(package
->location()))
1953 package
->set_location(location
);
1957 // First time we have seen this package name.
1958 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1959 go_assert(ins
.first
->second
== NULL
);
1960 ins
.first
->second
= package
;
1966 // Return the pkgpath symbol for a package, given the pkgpath.
1969 Gogo::pkgpath_symbol_for_package(const std::string
& pkgpath
)
1971 Packages::iterator p
= this->packages_
.find(pkgpath
);
1972 go_assert(p
!= this->packages_
.end());
1973 return p
->second
->pkgpath_symbol();
1976 // Start compiling a function.
1979 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1980 bool add_method_to_type
, Location location
)
1982 bool at_top_level
= this->functions_
.empty();
1984 Block
* block
= new Block(NULL
, location
);
1986 Named_object
* enclosing
= (at_top_level
1988 : this->functions_
.back().function
);
1990 Function
* function
= new Function(type
, enclosing
, block
, location
);
1992 if (type
->is_method())
1994 const Typed_identifier
* receiver
= type
->receiver();
1995 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1996 true, true, location
);
1997 std::string rname
= receiver
->name();
1998 unsigned rcounter
= 0;
2000 // We need to give a nameless receiver parameter a synthesized name to
2001 // avoid having it clash with some other nameless param. FIXME.
2002 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
2004 block
->bindings()->add_variable(rname
, NULL
, this_param
);
2007 const Typed_identifier_list
* parameters
= type
->parameters();
2008 bool is_varargs
= type
->is_varargs();
2009 unsigned pcounter
= 0;
2010 if (parameters
!= NULL
)
2012 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
2013 p
!= parameters
->end();
2016 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
2018 if (is_varargs
&& p
+ 1 == parameters
->end())
2019 param
->set_is_varargs_parameter();
2021 std::string pname
= p
->name();
2023 // We need to give each nameless parameter a non-empty name to avoid
2024 // having it clash with some other nameless param. FIXME.
2025 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
2027 block
->bindings()->add_variable(pname
, NULL
, param
);
2031 function
->create_result_variables(this);
2033 const std::string
* pname
;
2034 std::string nested_name
;
2035 bool is_init
= false;
2036 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
2038 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
2039 || (type
->results() != NULL
&& !type
->results()->empty()))
2040 go_error_at(location
,
2041 "func init must have no arguments and no return values");
2042 // There can be multiple "init" functions, so give them each a
2044 nested_name
= this->init_function_name();
2045 pname
= &nested_name
;
2048 else if (!name
.empty())
2052 // Invent a name for a nested function.
2053 nested_name
= this->nested_function_name(enclosing
);
2054 pname
= &nested_name
;
2058 if (Gogo::is_sink_name(*pname
))
2060 std::string
sname(this->sink_function_name());
2061 ret
= Named_object::make_function(sname
, NULL
, function
);
2062 ret
->func_value()->set_is_sink();
2064 if (!type
->is_method())
2065 ret
= this->package_
->bindings()->add_named_object(ret
);
2066 else if (add_method_to_type
)
2068 // We should report errors even for sink methods.
2069 Type
* rtype
= type
->receiver()->type();
2070 // Avoid points_to and deref to avoid getting an error if
2071 // the type is not yet defined.
2072 if (rtype
->classification() == Type::TYPE_POINTER
)
2073 rtype
= rtype
->points_to();
2074 while (rtype
->named_type() != NULL
2075 && rtype
->named_type()->is_alias())
2076 rtype
= rtype
->named_type()->real_type()->forwarded();
2077 if (rtype
->is_error_type())
2079 else if (rtype
->named_type() != NULL
)
2081 if (rtype
->named_type()->named_object()->package() != NULL
)
2082 go_error_at(type
->receiver()->location(),
2083 "may not define methods on non-local type");
2085 else if (rtype
->forward_declaration_type() != NULL
)
2087 // Go ahead and add the method in case we need to report
2088 // an error when we see the definition.
2089 rtype
->forward_declaration_type()->add_existing_method(ret
);
2092 go_error_at(type
->receiver()->location(),
2093 ("invalid receiver type "
2094 "(receiver must be a named type)"));
2097 else if (!type
->is_method())
2099 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
2100 if (!ret
->is_function() || ret
->func_value() != function
)
2102 // Redefinition error. Invent a name to avoid knockon
2104 std::string
rname(this->redefined_function_name());
2105 ret
= this->package_
->bindings()->add_function(rname
, NULL
, function
);
2110 if (!add_method_to_type
)
2111 ret
= Named_object::make_function(name
, NULL
, function
);
2114 go_assert(at_top_level
);
2115 Type
* rtype
= type
->receiver()->type();
2117 while (rtype
->named_type() != NULL
2118 && rtype
->named_type()->is_alias())
2119 rtype
= rtype
->named_type()->real_type()->forwarded();
2121 // We want to look through the pointer created by the
2122 // parser, without getting an error if the type is not yet
2124 if (rtype
->classification() == Type::TYPE_POINTER
)
2125 rtype
= rtype
->points_to();
2127 while (rtype
->named_type() != NULL
2128 && rtype
->named_type()->is_alias())
2129 rtype
= rtype
->named_type()->real_type()->forwarded();
2131 if (rtype
->is_error_type())
2132 ret
= Named_object::make_function(name
, NULL
, function
);
2133 else if (rtype
->named_type() != NULL
)
2135 if (rtype
->named_type()->named_object()->package() != NULL
)
2137 go_error_at(type
->receiver()->location(),
2138 "may not define methods on non-local type");
2139 ret
= Named_object::make_function(name
, NULL
, function
);
2143 ret
= rtype
->named_type()->add_method(name
, function
);
2144 if (!ret
->is_function())
2146 // Redefinition error.
2147 ret
= Named_object::make_function(name
, NULL
, function
);
2151 else if (rtype
->forward_declaration_type() != NULL
)
2153 Named_object
* type_no
=
2154 rtype
->forward_declaration_type()->named_object();
2155 if (type_no
->is_unknown())
2157 // If we are seeing methods it really must be a
2158 // type. Declare it as such. An alternative would
2159 // be to support lists of methods for unknown
2160 // expressions. Either way the error messages if
2161 // this is not a type are going to get confusing.
2162 Named_object
* declared
=
2163 this->declare_package_type(type_no
->name(),
2164 type_no
->location());
2166 == type_no
->unknown_value()->real_named_object());
2168 ret
= rtype
->forward_declaration_type()->add_method(name
,
2173 go_error_at(type
->receiver()->location(),
2174 ("invalid receiver type (receiver must "
2175 "be a named type)"));
2176 ret
= Named_object::make_function(name
, NULL
, function
);
2179 this->package_
->bindings()->add_method(ret
);
2182 this->functions_
.resize(this->functions_
.size() + 1);
2183 Open_function
& of(this->functions_
.back());
2185 of
.blocks
.push_back(block
);
2189 this->init_functions_
.push_back(ret
);
2190 this->need_init_fn_
= true;
2196 // Finish compiling a function.
2199 Gogo::finish_function(Location location
)
2201 this->finish_block(location
);
2202 go_assert(this->functions_
.back().blocks
.empty());
2203 this->functions_
.pop_back();
2206 // Return the current function.
2209 Gogo::current_function() const
2211 go_assert(!this->functions_
.empty());
2212 return this->functions_
.back().function
;
2215 // Start a new block.
2218 Gogo::start_block(Location location
)
2220 go_assert(!this->functions_
.empty());
2221 Block
* block
= new Block(this->current_block(), location
);
2222 this->functions_
.back().blocks
.push_back(block
);
2228 Gogo::finish_block(Location location
)
2230 go_assert(!this->functions_
.empty());
2231 go_assert(!this->functions_
.back().blocks
.empty());
2232 Block
* block
= this->functions_
.back().blocks
.back();
2233 this->functions_
.back().blocks
.pop_back();
2234 block
->set_end_location(location
);
2238 // Add an erroneous name.
2241 Gogo::add_erroneous_name(const std::string
& name
)
2243 return this->package_
->bindings()->add_erroneous_name(name
);
2246 // Add an unknown name.
2249 Gogo::add_unknown_name(const std::string
& name
, Location location
)
2251 return this->package_
->bindings()->add_unknown_name(name
, location
);
2254 // Declare a function.
2257 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
2260 if (!type
->is_method())
2261 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
2265 // We don't bother to add this to the list of global
2267 Type
* rtype
= type
->receiver()->type();
2269 while (rtype
->named_type() != NULL
2270 && rtype
->named_type()->is_alias())
2271 rtype
= rtype
->named_type()->real_type()->forwarded();
2273 // We want to look through the pointer created by the
2274 // parser, without getting an error if the type is not yet
2276 if (rtype
->classification() == Type::TYPE_POINTER
)
2277 rtype
= rtype
->points_to();
2279 while (rtype
->named_type() != NULL
2280 && rtype
->named_type()->is_alias())
2281 rtype
= rtype
->named_type()->real_type()->forwarded();
2283 if (rtype
->is_error_type())
2285 else if (rtype
->named_type() != NULL
)
2286 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
2288 else if (rtype
->forward_declaration_type() != NULL
)
2290 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
2291 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
2295 go_error_at(type
->receiver()->location(),
2296 "invalid receiver type (receiver must be a named type)");
2297 return Named_object::make_erroneous_name(name
);
2302 // Add a label definition.
2305 Gogo::add_label_definition(const std::string
& label_name
,
2308 go_assert(!this->functions_
.empty());
2309 Function
* func
= this->functions_
.back().function
->func_value();
2310 Label
* label
= func
->add_label_definition(this, label_name
, location
);
2311 this->add_statement(Statement::make_label_statement(label
, location
));
2315 // Add a label reference.
2318 Gogo::add_label_reference(const std::string
& label_name
,
2319 Location location
, bool issue_goto_errors
)
2321 go_assert(!this->functions_
.empty());
2322 Function
* func
= this->functions_
.back().function
->func_value();
2323 return func
->add_label_reference(this, label_name
, location
,
2327 // Return the current binding state.
2330 Gogo::bindings_snapshot(Location location
)
2332 return new Bindings_snapshot(this->current_block(), location
);
2338 Gogo::add_statement(Statement
* statement
)
2340 go_assert(!this->functions_
.empty()
2341 && !this->functions_
.back().blocks
.empty());
2342 this->functions_
.back().blocks
.back()->add_statement(statement
);
2348 Gogo::add_block(Block
* block
, Location location
)
2350 go_assert(!this->functions_
.empty()
2351 && !this->functions_
.back().blocks
.empty());
2352 Statement
* statement
= Statement::make_block_statement(block
, location
);
2353 this->functions_
.back().blocks
.back()->add_statement(statement
);
2359 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2362 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2368 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2370 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2372 if (!this->in_global_scope() && no
->is_type())
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_value()->set_in_function(f
, index
);
2384 // Add a named type.
2387 Gogo::add_named_type(Named_type
* type
)
2389 go_assert(this->in_global_scope());
2390 this->current_bindings()->add_named_type(type
);
2396 Gogo::declare_type(const std::string
& name
, Location location
)
2398 Bindings
* bindings
= this->current_bindings();
2399 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2400 if (!this->in_global_scope() && no
->is_type_declaration())
2402 Named_object
* f
= this->functions_
.back().function
;
2404 if (f
->is_function())
2405 index
= f
->func_value()->new_local_type_index();
2408 no
->type_declaration_value()->set_in_function(f
, index
);
2413 // Declare a type at the package level.
2416 Gogo::declare_package_type(const std::string
& name
, Location location
)
2418 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2421 // Declare a function at the package level.
2424 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2427 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2431 // Add a function declaration to the list of functions we may want to
2435 Gogo::add_imported_inlinable_function(Named_object
* no
)
2437 go_assert(no
->is_function_declaration());
2438 Function_declaration
* fd
= no
->func_declaration_value();
2439 if (fd
->is_on_inlinable_list())
2441 this->imported_inlinable_functions_
.push_back(no
);
2442 fd
->set_is_on_inlinable_list();
2445 // Define a type which was already declared.
2448 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2450 this->current_bindings()->define_type(no
, type
);
2456 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2458 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2461 // In a function the middle-end wants to see a DECL_EXPR node.
2463 && no
->is_variable()
2464 && !no
->var_value()->is_parameter()
2465 && !this->functions_
.empty())
2466 this->add_statement(Statement::make_variable_declaration(no
));
2472 Gogo::rename_if_empty(std::string
* pname
, const char* tag
, unsigned* count
)
2474 if (pname
->empty() || Gogo::is_sink_name(*pname
))
2477 go_assert(strlen(tag
) < 10);
2478 snprintf(buf
, sizeof buf
, "%s.%u", tag
, *count
);
2485 // Add a sink--a reference to the blank identifier _.
2490 return Named_object::make_sink();
2493 // Add a named object for a dot import.
2496 Gogo::add_dot_import_object(Named_object
* no
)
2498 // If the name already exists, then it was defined in some file seen
2499 // earlier. If the earlier name is just a declaration, don't add
2500 // this name, because that will cause the previous declaration to
2501 // merge to this imported name, which should not happen. Just add
2502 // this name to the list of file block names to get appropriate
2503 // errors if we see a later definition.
2504 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2505 if (e
!= NULL
&& e
->package() == NULL
)
2507 if (e
->is_unknown())
2509 if (e
->package() == NULL
2510 && (e
->is_type_declaration()
2511 || e
->is_function_declaration()
2512 || e
->is_unknown()))
2514 this->add_file_block_name(no
->name(), no
->location());
2519 this->current_bindings()->add_named_object(no
);
2522 // Add a linkname. This implements the go:linkname compiler directive.
2523 // We only support this for functions and function declarations.
2526 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2527 const std::string
& ext_name
, Location loc
)
2530 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2533 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2534 else if (no
->is_function())
2536 if (ext_name
.empty())
2537 no
->func_value()->set_is_exported_by_linkname();
2539 no
->func_value()->set_asm_name(ext_name
);
2541 else if (no
->is_function_declaration())
2543 if (ext_name
.empty())
2545 ("%<//go:linkname%> missing external name "
2546 "for declaration of %s"),
2549 no
->func_declaration_value()->set_asm_name(ext_name
);
2553 ("%s is not a function; "
2554 "%<//go:linkname%> is only supported for functions"),
2558 // Mark all local variables used. This is used when some types of
2559 // parse error occur.
2562 Gogo::mark_locals_used()
2564 for (Open_functions::iterator pf
= this->functions_
.begin();
2565 pf
!= this->functions_
.end();
2568 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2569 pb
!= pf
->blocks
.end();
2571 (*pb
)->bindings()->mark_locals_used();
2575 // Record that we've seen an interface type.
2578 Gogo::record_interface_type(Interface_type
* itype
)
2580 this->interface_types_
.push_back(itype
);
2583 // Define the global names. We do this only after parsing all the
2584 // input files, because the program might define the global names
2588 Gogo::define_global_names()
2590 if (this->is_main_package())
2592 // Every Go program has to import the runtime package, so that
2593 // it is properly initialized. We can't use
2594 // predeclared_location here as it will cause runtime functions
2595 // to appear to be builtin functions.
2596 this->import_package("runtime", "_", false, false,
2597 this->package_
->location());
2600 for (Bindings::const_declarations_iterator p
=
2601 this->globals_
->begin_declarations();
2602 p
!= this->globals_
->end_declarations();
2605 Named_object
* global_no
= p
->second
;
2606 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2607 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2611 if (no
->is_type_declaration())
2613 if (global_no
->is_type())
2615 if (no
->type_declaration_value()->has_methods())
2617 for (std::vector
<Named_object
*>::const_iterator pm
=
2618 no
->type_declaration_value()->methods()->begin();
2619 pm
!= no
->type_declaration_value()->methods()->end();
2621 go_error_at((*pm
)->location(),
2622 "may not define methods on non-local type");
2624 no
->set_type_value(global_no
->type_value());
2628 go_error_at(no
->location(), "expected type");
2629 Type
* errtype
= Type::make_error_type();
2631 Named_object::make_type("erroneous_type", NULL
, errtype
,
2632 Linemap::predeclared_location());
2633 no
->set_type_value(err
->type_value());
2636 else if (no
->is_unknown())
2637 no
->unknown_value()->set_real_named_object(global_no
);
2640 // Give an error if any name is defined in both the package block
2641 // and the file block. For example, this can happen if one file
2642 // imports "fmt" and another file defines a global variable fmt.
2643 for (Bindings::const_declarations_iterator p
=
2644 this->package_
->bindings()->begin_declarations();
2645 p
!= this->package_
->bindings()->end_declarations();
2648 if (p
->second
->is_unknown()
2649 && p
->second
->unknown_value()->real_named_object() == NULL
)
2651 // No point in warning about an undefined name, as we will
2652 // get other errors later anyhow.
2655 File_block_names::const_iterator pf
=
2656 this->file_block_names_
.find(p
->second
->name());
2657 if (pf
!= this->file_block_names_
.end())
2659 std::string n
= p
->second
->message_name();
2660 go_error_at(p
->second
->location(),
2661 "%qs defined as both imported name and global name",
2663 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2666 // No package scope identifier may be named "init".
2667 if (!p
->second
->is_function()
2668 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2670 go_error_at(p
->second
->location(),
2671 "cannot declare init - must be func");
2676 // Clear out names in file scope.
2679 Gogo::clear_file_scope()
2681 this->package_
->bindings()->clear_file_scope(this);
2683 // Warn about packages which were imported but not used.
2684 bool quiet
= saw_errors();
2685 for (Packages::iterator p
= this->packages_
.begin();
2686 p
!= this->packages_
.end();
2689 Package
* package
= p
->second
;
2690 if (package
!= this->package_
&& !quiet
)
2692 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2693 p1
!= package
->aliases().end();
2696 if (!p1
->second
->used())
2698 // Give a more refined error message if the alias name is known.
2699 std::string pkg_name
= package
->package_name();
2700 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2702 go_error_at(p1
->second
->location(),
2703 "imported and not used: %s as %s",
2704 Gogo::message_name(pkg_name
).c_str(),
2705 Gogo::message_name(p1
->first
).c_str());
2708 go_error_at(p1
->second
->location(),
2709 "imported and not used: %s",
2710 Gogo::message_name(pkg_name
).c_str());
2714 package
->clear_used();
2717 this->current_file_imported_unsafe_
= false;
2720 // Queue up a type-specific hash function for later writing. These
2721 // are written out in write_specific_type_functions, called after the
2722 // parse tree is lowered.
2725 Gogo::queue_hash_function(Type
* type
, int64_t size
,
2726 const std::string
& hash_name
,
2727 Function_type
* hash_fntype
)
2729 go_assert(!this->specific_type_functions_are_written_
);
2730 go_assert(!this->in_global_scope());
2731 Specific_type_function::Specific_type_function_kind kind
=
2732 Specific_type_function::SPECIFIC_HASH
;
2733 Specific_type_function
* tsf
= new Specific_type_function(type
, NULL
, size
,
2736 this->specific_type_functions_
.push_back(tsf
);
2739 // Queue up a type-specific equal function for later writing. These
2740 // are written out in write_specific_type_functions, called after the
2741 // parse tree is lowered.
2744 Gogo::queue_equal_function(Type
* type
, Named_type
* name
, int64_t size
,
2745 const std::string
& equal_name
,
2746 Function_type
* equal_fntype
)
2748 go_assert(!this->specific_type_functions_are_written_
);
2749 go_assert(!this->in_global_scope());
2750 Specific_type_function::Specific_type_function_kind kind
=
2751 Specific_type_function::SPECIFIC_EQUAL
;
2752 Specific_type_function
* tsf
= new Specific_type_function(type
, name
, size
,
2755 this->specific_type_functions_
.push_back(tsf
);
2758 // Look for types which need specific hash or equality functions.
2760 class Specific_type_functions
: public Traverse
2763 Specific_type_functions(Gogo
* gogo
)
2764 : Traverse(traverse_types
),
2776 Specific_type_functions::type(Type
* t
)
2778 switch (t
->classification())
2780 case Type::TYPE_NAMED
:
2782 Named_type
* nt
= t
->named_type();
2784 return TRAVERSE_CONTINUE
;
2785 if (t
->needs_specific_type_functions(this->gogo_
))
2786 t
->equal_function(this->gogo_
, nt
, NULL
);
2788 // If this is a struct type, we don't want to make functions
2789 // for the unnamed struct.
2790 Type
* rt
= nt
->real_type();
2791 if (rt
->struct_type() == NULL
)
2793 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2794 return TRAVERSE_EXIT
;
2798 // If this type is defined in another package, then we don't
2799 // need to worry about the unexported fields.
2800 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2801 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2802 for (Struct_field_list::const_iterator p
= fields
->begin();
2806 if (is_defined_elsewhere
2807 && Gogo::is_hidden_name(p
->field_name()))
2809 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2810 return TRAVERSE_EXIT
;
2814 return TRAVERSE_SKIP_COMPONENTS
;
2817 case Type::TYPE_STRUCT
:
2818 case Type::TYPE_ARRAY
:
2819 if (t
->needs_specific_type_functions(this->gogo_
))
2820 t
->equal_function(this->gogo_
, NULL
, NULL
);
2823 case Type::TYPE_MAP
:
2825 Type
* key_type
= t
->map_type()->key_type();
2826 if (key_type
->needs_specific_type_functions(this->gogo_
))
2827 key_type
->hash_function(this->gogo_
, NULL
);
2835 return TRAVERSE_CONTINUE
;
2838 // Write out type specific functions.
2841 Gogo::write_specific_type_functions()
2843 Specific_type_functions
stf(this);
2844 this->traverse(&stf
);
2846 while (!this->specific_type_functions_
.empty())
2848 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2849 this->specific_type_functions_
.pop_back();
2850 if (tsf
->kind
== Specific_type_function::SPECIFIC_HASH
)
2851 tsf
->type
->write_hash_function(this, tsf
->size
, tsf
->fnname
,
2854 tsf
->type
->write_equal_function(this, tsf
->name
, tsf
->size
,
2855 tsf
->fnname
, tsf
->fntype
);
2858 this->specific_type_functions_are_written_
= true;
2861 // Traverse the tree.
2864 Gogo::traverse(Traverse
* traverse
)
2866 // Traverse the current package first for consistency. The other
2867 // packages will only contain imported types, constants, and
2869 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2871 for (Packages::const_iterator p
= this->packages_
.begin();
2872 p
!= this->packages_
.end();
2875 if (p
->second
!= this->package_
)
2877 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2883 // Add a type to verify. This is used for types of sink variables, in
2884 // order to give appropriate error messages.
2887 Gogo::add_type_to_verify(Type
* type
)
2889 this->verify_types_
.push_back(type
);
2892 // Traversal class used to verify types.
2894 class Verify_types
: public Traverse
2898 : Traverse(traverse_types
)
2905 // Verify that a type is correct.
2908 Verify_types::type(Type
* t
)
2911 return TRAVERSE_SKIP_COMPONENTS
;
2912 return TRAVERSE_CONTINUE
;
2915 // Verify that all types are correct.
2918 Gogo::verify_types()
2920 Verify_types traverse
;
2921 this->traverse(&traverse
);
2923 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2924 p
!= this->verify_types_
.end();
2927 this->verify_types_
.clear();
2930 // Traversal class used to lower parse tree.
2932 class Lower_parse_tree
: public Traverse
2935 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2936 : Traverse(traverse_variables
2937 | traverse_constants
2938 | traverse_functions
2939 | traverse_statements
2940 | traverse_expressions
),
2941 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2945 set_inserter(const Statement_inserter
* inserter
)
2946 { this->inserter_
= *inserter
; }
2949 variable(Named_object
*);
2952 constant(Named_object
*, bool);
2955 function(Named_object
*);
2958 statement(Block
*, size_t* pindex
, Statement
*);
2961 expression(Expression
**);
2966 // The function we are traversing.
2967 Named_object
* function_
;
2968 // Value to use for the predeclared constant iota.
2970 // Current statement inserter for use by expressions.
2971 Statement_inserter inserter_
;
2977 Lower_parse_tree::variable(Named_object
* no
)
2979 if (!no
->is_variable())
2980 return TRAVERSE_CONTINUE
;
2982 if (no
->is_variable() && no
->var_value()->is_global())
2984 // Global variables can have loops in their initialization
2985 // expressions. This is handled in lower_init_expression.
2986 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2988 return TRAVERSE_CONTINUE
;
2991 // This is a local variable. We are going to return
2992 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2993 // initialization expression when we reach the variable declaration
2994 // statement. However, that means that we need to traverse the type
2996 if (no
->var_value()->has_type())
2998 Type
* type
= no
->var_value()->type();
3001 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
3002 return TRAVERSE_EXIT
;
3005 go_assert(!no
->var_value()->has_pre_init());
3007 return TRAVERSE_SKIP_COMPONENTS
;
3010 // Lower constants. We handle constants specially so that we can set
3011 // the right value for the predeclared constant iota. This works in
3012 // conjunction with the way we lower Const_expression objects.
3015 Lower_parse_tree::constant(Named_object
* no
, bool)
3017 Named_constant
* nc
= no
->const_value();
3019 // Don't get into trouble if the constant's initializer expression
3020 // refers to the constant itself.
3022 return TRAVERSE_CONTINUE
;
3025 go_assert(this->iota_value_
== -1);
3026 this->iota_value_
= nc
->iota_value();
3027 nc
->traverse_expression(this);
3028 this->iota_value_
= -1;
3030 nc
->clear_lowering();
3032 // We will traverse the expression a second time, but that will be
3035 return TRAVERSE_CONTINUE
;
3038 // Lower the body of a function, and set the closure type. Record the
3039 // function while lowering it, so that we can pass it down when
3040 // lowering an expression.
3043 Lower_parse_tree::function(Named_object
* no
)
3045 no
->func_value()->set_closure_type();
3047 go_assert(this->function_
== NULL
);
3048 this->function_
= no
;
3049 int t
= no
->func_value()->traverse(this);
3050 this->function_
= NULL
;
3052 if (t
== TRAVERSE_EXIT
)
3054 return TRAVERSE_SKIP_COMPONENTS
;
3057 // Lower statement parse trees.
3060 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3062 // Because we explicitly traverse the statement's contents
3063 // ourselves, we want to skip block statements here. There is
3064 // nothing to lower in a block statement.
3065 if (sorig
->is_block_statement())
3066 return TRAVERSE_CONTINUE
;
3068 Statement_inserter
hold_inserter(this->inserter_
);
3069 this->inserter_
= Statement_inserter(block
, pindex
);
3071 // Lower the expressions first.
3072 int t
= sorig
->traverse_contents(this);
3073 if (t
== TRAVERSE_EXIT
)
3075 this->inserter_
= hold_inserter
;
3079 // Keep lowering until nothing changes.
3080 Statement
* s
= sorig
;
3083 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
3088 t
= s
->traverse_contents(this);
3089 if (t
== TRAVERSE_EXIT
)
3091 this->inserter_
= hold_inserter
;
3097 block
->replace_statement(*pindex
, s
);
3099 this->inserter_
= hold_inserter
;
3100 return TRAVERSE_SKIP_COMPONENTS
;
3103 // Lower expression parse trees.
3106 Lower_parse_tree::expression(Expression
** pexpr
)
3108 // We have to lower all subexpressions first, so that we can get
3109 // their type if necessary. This is awkward, because we don't have
3110 // a postorder traversal pass.
3111 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3112 return TRAVERSE_EXIT
;
3113 // Keep lowering until nothing changes.
3116 Expression
* e
= *pexpr
;
3117 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
3118 &this->inserter_
, this->iota_value_
);
3121 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3122 return TRAVERSE_EXIT
;
3126 // Lower the type of this expression before the parent looks at it,
3127 // in case the type contains an array that has expressions in its
3128 // length. Skip an Unknown_expression, as at this point that means
3129 // a composite literal key that does not have a type.
3130 if ((*pexpr
)->unknown_expression() == NULL
)
3131 Type::traverse((*pexpr
)->type(), this);
3133 return TRAVERSE_SKIP_COMPONENTS
;
3136 // Lower the parse tree. This is called after the parse is complete,
3137 // when all names should be resolved.
3140 Gogo::lower_parse_tree()
3142 Lower_parse_tree
lower_parse_tree(this, NULL
);
3143 this->traverse(&lower_parse_tree
);
3145 // If we found any functions defined in other packages that are
3146 // inlinables, import their bodies and turn them into functions.
3148 // Note that as we import inlinable functions we may find more
3149 // inlinable functions, so don't use an iterator.
3150 for (size_t i
= 0; i
< this->imported_inlinable_functions_
.size(); i
++)
3152 Named_object
* no
= this->imported_inlinable_functions_
[i
];
3153 no
->func_declaration_value()->import_function_body(this, no
);
3156 // There might be type definitions that involve expressions such as the
3157 // array length. Make sure to lower these expressions as well. Otherwise,
3158 // errors hidden within a type can introduce unexpected errors into later
3160 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
3161 p
!= this->verify_types_
.end();
3163 Type::traverse(*p
, &lower_parse_tree
);
3169 Gogo::lower_block(Named_object
* function
, Block
* block
)
3171 Lower_parse_tree
lower_parse_tree(this, function
);
3172 block
->traverse(&lower_parse_tree
);
3175 // Lower an expression. INSERTER may be NULL, in which case the
3176 // expression had better not need to create any temporaries.
3179 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
3182 Lower_parse_tree
lower_parse_tree(this, function
);
3183 if (inserter
!= NULL
)
3184 lower_parse_tree
.set_inserter(inserter
);
3185 lower_parse_tree
.expression(pexpr
);
3188 // Lower a constant. This is called when lowering a reference to a
3189 // constant. We have to make sure that the constant has already been
3193 Gogo::lower_constant(Named_object
* no
)
3195 go_assert(no
->is_const());
3196 Lower_parse_tree
lower(this, NULL
);
3197 lower
.constant(no
, false);
3200 // Make implicit type conversions explicit. Currently only does for
3201 // interface conversions, so the escape analysis can see them and
3204 class Add_conversions
: public Traverse
3208 : Traverse(traverse_statements
3209 | traverse_expressions
)
3213 statement(Block
*, size_t* pindex
, Statement
*);
3216 expression(Expression
**);
3219 // Add explicit conversions in a statement.
3222 Add_conversions::statement(Block
*, size_t*, Statement
* sorig
)
3224 sorig
->add_conversions();
3225 return TRAVERSE_CONTINUE
;
3228 // Add explicit conversions in an expression.
3231 Add_conversions::expression(Expression
** pexpr
)
3233 (*pexpr
)->add_conversions();
3234 return TRAVERSE_CONTINUE
;
3238 Gogo::add_conversions()
3240 Add_conversions add_conversions
;
3241 this->traverse(&add_conversions
);
3245 Gogo::add_conversions_in_block(Block
*b
)
3247 Add_conversions add_conversions
;
3248 b
->traverse(&add_conversions
);
3251 // Traversal class for simple deadcode elimination.
3253 class Remove_deadcode
: public Traverse
3257 : Traverse(traverse_statements
3258 | traverse_expressions
)
3262 statement(Block
*, size_t* pindex
, Statement
*);
3265 expression(Expression
**);
3268 // Remove deadcode in a statement.
3271 Remove_deadcode::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3273 Location loc
= sorig
->location();
3274 If_statement
* ifs
= sorig
->if_statement();
3277 // Remove the dead branch of an if statement.
3279 if (ifs
->condition()->boolean_constant_value(&bval
))
3283 s
= Statement::make_block_statement(ifs
->then_block(),
3286 if (ifs
->else_block() != NULL
)
3287 s
= Statement::make_block_statement(ifs
->else_block(),
3290 // Make a dummy statement.
3291 s
= Statement::make_statement(Expression::make_boolean(false, loc
),
3294 block
->replace_statement(*pindex
, s
);
3297 return TRAVERSE_CONTINUE
;
3300 // Remove deadcode in an expression.
3303 Remove_deadcode::expression(Expression
** pexpr
)
3305 // Discard the right arm of a shortcut expression of constant value.
3306 Binary_expression
* be
= (*pexpr
)->binary_expression();
3309 && be
->boolean_constant_value(&bval
)
3310 && (be
->op() == OPERATOR_ANDAND
3311 || be
->op() == OPERATOR_OROR
))
3312 *pexpr
= Expression::make_boolean(bval
, be
->location());
3313 return TRAVERSE_CONTINUE
;
3319 Gogo::remove_deadcode()
3321 Remove_deadcode remove_deadcode
;
3322 this->traverse(&remove_deadcode
);
3325 // Traverse the tree to create function descriptors as needed.
3327 class Create_function_descriptors
: public Traverse
3330 Create_function_descriptors(Gogo
* gogo
)
3331 : Traverse(traverse_functions
| traverse_expressions
),
3336 function(Named_object
*);
3339 expression(Expression
**);
3345 // Create a descriptor for every top-level exported function.
3348 Create_function_descriptors::function(Named_object
* no
)
3350 if (no
->is_function()
3351 && no
->func_value()->enclosing() == NULL
3352 && !no
->func_value()->is_method()
3353 && !Gogo::is_hidden_name(no
->name())
3354 && !Gogo::is_thunk(no
))
3355 no
->func_value()->descriptor(this->gogo_
, no
);
3357 return TRAVERSE_CONTINUE
;
3360 // If we see a function referenced in any way other than calling it,
3361 // create a descriptor for it.
3364 Create_function_descriptors::expression(Expression
** pexpr
)
3366 Expression
* expr
= *pexpr
;
3368 Func_expression
* fe
= expr
->func_expression();
3371 // We would not get here for a call to this function, so this is
3372 // a reference to a function other than calling it. We need a
3374 if (fe
->closure() != NULL
)
3375 return TRAVERSE_CONTINUE
;
3376 Named_object
* no
= fe
->named_object();
3377 if (no
->is_function() && !no
->func_value()->is_method())
3378 no
->func_value()->descriptor(this->gogo_
, no
);
3379 else if (no
->is_function_declaration()
3380 && !no
->func_declaration_value()->type()->is_method()
3381 && !Linemap::is_predeclared_location(no
->location()))
3382 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
3383 return TRAVERSE_CONTINUE
;
3386 Bound_method_expression
* bme
= expr
->bound_method_expression();
3389 // We would not get here for a call to this method, so this is a
3390 // method value. We need to create a thunk.
3391 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
3393 return TRAVERSE_CONTINUE
;
3396 Interface_field_reference_expression
* ifre
=
3397 expr
->interface_field_reference_expression();
3400 // We would not get here for a call to this interface method, so
3401 // this is a method value. We need to create a thunk.
3402 Interface_type
* type
= ifre
->expr()->type()->interface_type();
3404 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
3406 return TRAVERSE_CONTINUE
;
3409 Call_expression
* ce
= expr
->call_expression();
3412 Expression
* fn
= ce
->fn();
3413 if (fn
->func_expression() != NULL
3414 || fn
->bound_method_expression() != NULL
3415 || fn
->interface_field_reference_expression() != NULL
)
3417 // Traverse the arguments but not the function.
3418 Expression_list
* args
= ce
->args();
3421 if (args
->traverse(this) == TRAVERSE_EXIT
)
3422 return TRAVERSE_EXIT
;
3424 return TRAVERSE_SKIP_COMPONENTS
;
3428 return TRAVERSE_CONTINUE
;
3431 // Create function descriptors as needed. We need a function
3432 // descriptor for all exported functions and for all functions that
3433 // are referenced without being called.
3436 Gogo::create_function_descriptors()
3438 // Create a function descriptor for any exported function that is
3439 // declared in this package. This is so that we have a descriptor
3440 // for functions written in assembly. Gather the descriptors first
3441 // so that we don't add declarations while looping over them.
3442 std::vector
<Named_object
*> fndecls
;
3443 Bindings
* b
= this->package_
->bindings();
3444 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
3445 p
!= b
->end_declarations();
3448 Named_object
* no
= p
->second
;
3449 if (no
->is_function_declaration()
3450 && !no
->func_declaration_value()->type()->is_method()
3451 && !Linemap::is_predeclared_location(no
->location())
3452 && !Gogo::is_hidden_name(no
->name()))
3453 fndecls
.push_back(no
);
3455 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
3458 (*p
)->func_declaration_value()->descriptor(this, *p
);
3461 Create_function_descriptors
cfd(this);
3462 this->traverse(&cfd
);
3465 // Finalize the methods of an interface type.
3468 Finalize_methods::type(Type
* t
)
3470 // Check the classification so that we don't finalize the methods
3471 // twice for a named interface type.
3472 switch (t
->classification())
3474 case Type::TYPE_INTERFACE
:
3475 t
->interface_type()->finalize_methods();
3478 case Type::TYPE_NAMED
:
3480 Named_type
* nt
= t
->named_type();
3481 Type
* rt
= nt
->real_type();
3482 if (rt
->classification() != Type::TYPE_STRUCT
)
3484 // Finalize the methods of the real type first.
3485 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
3486 return TRAVERSE_EXIT
;
3488 // Finalize the methods of this type.
3489 nt
->finalize_methods(this->gogo_
);
3493 // We don't want to finalize the methods of a named struct
3494 // type, as the methods should be attached to the named
3495 // type, not the struct type. We just want to finalize
3498 // It is possible that a field type refers indirectly to
3499 // this type, such as via a field with function type with
3500 // an argument or result whose type is this type. To
3501 // avoid the cycle, first finalize the methods of any
3502 // embedded types, which are the only types we need to
3503 // know to finalize the methods of this type.
3504 const Struct_field_list
* fields
= rt
->struct_type()->fields();
3507 for (Struct_field_list::const_iterator pf
= fields
->begin();
3508 pf
!= fields
->end();
3511 if (pf
->is_anonymous())
3513 if (Type::traverse(pf
->type(), this) == TRAVERSE_EXIT
)
3514 return TRAVERSE_EXIT
;
3519 // Finalize the methods of this type.
3520 nt
->finalize_methods(this->gogo_
);
3522 // Finalize all the struct fields.
3523 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3524 return TRAVERSE_EXIT
;
3527 // If this type is defined in a different package, then finalize the
3528 // types of all the methods, since we won't see them otherwise.
3529 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
3531 const Methods
* methods
= nt
->methods();
3532 for (Methods::const_iterator p
= methods
->begin();
3533 p
!= methods
->end();
3536 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
3537 return TRAVERSE_EXIT
;
3541 // Finalize the types of all methods that are declared but not
3542 // defined, since we won't see the declarations otherwise.
3543 if (nt
->named_object()->package() == NULL
3544 && nt
->local_methods() != NULL
)
3546 const Bindings
* methods
= nt
->local_methods();
3547 for (Bindings::const_declarations_iterator p
=
3548 methods
->begin_declarations();
3549 p
!= methods
->end_declarations();
3552 if (p
->second
->is_function_declaration())
3554 Type
* mt
= p
->second
->func_declaration_value()->type();
3555 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3556 return TRAVERSE_EXIT
;
3561 return TRAVERSE_SKIP_COMPONENTS
;
3564 case Type::TYPE_STRUCT
:
3565 // Traverse the field types first in case there is an embedded
3566 // field with methods that the struct should inherit.
3567 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3568 return TRAVERSE_EXIT
;
3569 t
->struct_type()->finalize_methods(this->gogo_
);
3570 return TRAVERSE_SKIP_COMPONENTS
;
3576 return TRAVERSE_CONTINUE
;
3579 // Finalize method lists and build stub methods for types.
3582 Gogo::finalize_methods()
3584 Finalize_methods
finalize(this);
3585 this->traverse(&finalize
);
3588 // Finalize the method list for a type. This is called when a type is
3589 // parsed for an inlined function body, which happens after the
3590 // finalize_methods pass.
3593 Gogo::finalize_methods_for_type(Type
* type
)
3595 Finalize_methods
finalize(this);
3596 Type::traverse(type
, &finalize
);
3599 // Set types for unspecified variables and constants.
3602 Gogo::determine_types()
3604 Bindings
* bindings
= this->current_bindings();
3605 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3606 p
!= bindings
->end_definitions();
3609 if ((*p
)->is_function())
3610 (*p
)->func_value()->determine_types();
3611 else if ((*p
)->is_variable())
3612 (*p
)->var_value()->determine_type();
3613 else if ((*p
)->is_const())
3614 (*p
)->const_value()->determine_type();
3616 // See if a variable requires us to build an initialization
3617 // function. We know that we will see all global variables
3619 if (!this->need_init_fn_
&& (*p
)->is_variable())
3621 Variable
* variable
= (*p
)->var_value();
3623 // If this is a global variable which requires runtime
3624 // initialization, we need an initialization function.
3625 if (!variable
->is_global())
3627 else if (variable
->init() == NULL
)
3629 else if (variable
->type()->interface_type() != NULL
)
3630 this->need_init_fn_
= true;
3631 else if (variable
->init()->is_constant())
3633 else if (!variable
->init()->is_composite_literal())
3634 this->need_init_fn_
= true;
3635 else if (variable
->init()->is_nonconstant_composite_literal())
3636 this->need_init_fn_
= true;
3638 // If this is a global variable which holds a pointer value,
3639 // then we need an initialization function to register it as a
3641 if (variable
->is_global() && variable
->type()->has_pointer())
3642 this->need_init_fn_
= true;
3646 // Determine the types of constants in packages.
3647 for (Packages::const_iterator p
= this->packages_
.begin();
3648 p
!= this->packages_
.end();
3650 p
->second
->determine_types();
3653 // Traversal class used for type checking.
3655 class Check_types_traverse
: public Traverse
3658 Check_types_traverse(Gogo
* gogo
)
3659 : Traverse(traverse_variables
3660 | traverse_constants
3661 | traverse_functions
3662 | traverse_statements
3663 | traverse_expressions
),
3668 variable(Named_object
*);
3671 constant(Named_object
*, bool);
3674 function(Named_object
*);
3677 statement(Block
*, size_t* pindex
, Statement
*);
3680 expression(Expression
**);
3687 // Check that a variable initializer has the right type.
3690 Check_types_traverse::variable(Named_object
* named_object
)
3692 if (named_object
->is_variable())
3694 Variable
* var
= named_object
->var_value();
3696 // Give error if variable type is not defined.
3697 var
->type()->base();
3699 Expression
* init
= var
->init();
3702 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3705 go_error_at(var
->location(), "incompatible type in initialization");
3707 go_error_at(var
->location(),
3708 "incompatible type in initialization (%s)",
3710 init
= Expression::make_error(named_object
->location());
3713 else if (init
!= NULL
3714 && init
->func_expression() != NULL
)
3716 Named_object
* no
= init
->func_expression()->named_object();
3717 Function_type
* fntype
;
3718 if (no
->is_function())
3719 fntype
= no
->func_value()->type();
3720 else if (no
->is_function_declaration())
3721 fntype
= no
->func_declaration_value()->type();
3725 // Builtin functions cannot be used as function values for variable
3727 if (fntype
->is_builtin())
3729 go_error_at(init
->location(),
3730 "invalid use of special built-in function %qs; "
3732 no
->message_name().c_str());
3736 && !var
->is_global()
3737 && !var
->is_parameter()
3738 && !var
->is_receiver()
3739 && !var
->type()->is_error()
3740 && (init
== NULL
|| !init
->is_error_expression())
3741 && !Lex::is_invalid_identifier(named_object
->name()))
3742 go_error_at(var
->location(), "%qs declared and not used",
3743 named_object
->message_name().c_str());
3745 return TRAVERSE_CONTINUE
;
3748 // Check that a constant initializer has the right type.
3751 Check_types_traverse::constant(Named_object
* named_object
, bool)
3753 Named_constant
* constant
= named_object
->const_value();
3754 Type
* ctype
= constant
->type();
3755 if (ctype
->integer_type() == NULL
3756 && ctype
->float_type() == NULL
3757 && ctype
->complex_type() == NULL
3758 && !ctype
->is_boolean_type()
3759 && !ctype
->is_string_type())
3761 if (ctype
->is_nil_type())
3762 go_error_at(constant
->location(), "const initializer cannot be nil");
3763 else if (!ctype
->is_error())
3764 go_error_at(constant
->location(), "invalid constant type");
3765 constant
->set_error();
3767 else if (!constant
->expr()->is_constant())
3769 go_error_at(constant
->expr()->location(), "expression is not constant");
3770 constant
->set_error();
3772 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3775 go_error_at(constant
->location(),
3776 "initialization expression has wrong type");
3777 constant
->set_error();
3779 return TRAVERSE_CONTINUE
;
3782 // There are no types to check in a function, but this is where we
3783 // issue warnings about labels which are defined but not referenced.
3786 Check_types_traverse::function(Named_object
* no
)
3788 no
->func_value()->check_labels();
3789 return TRAVERSE_CONTINUE
;
3792 // Check that types are valid in a statement.
3795 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3797 s
->check_types(this->gogo_
);
3798 return TRAVERSE_CONTINUE
;
3801 // Check that types are valid in an expression.
3804 Check_types_traverse::expression(Expression
** expr
)
3806 (*expr
)->check_types(this->gogo_
);
3807 return TRAVERSE_CONTINUE
;
3810 // Check that types are valid.
3815 Check_types_traverse
traverse(this);
3816 this->traverse(&traverse
);
3818 Bindings
* bindings
= this->current_bindings();
3819 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3820 p
!= bindings
->end_declarations();
3823 // Also check the types in a function declaration's signature.
3824 Named_object
* no
= p
->second
;
3825 if (no
->is_function_declaration())
3826 no
->func_declaration_value()->check_types();
3830 // Check the types in a single block.
3833 Gogo::check_types_in_block(Block
* block
)
3835 Check_types_traverse
traverse(this);
3836 block
->traverse(&traverse
);
3839 // A traversal class which finds all the expressions which must be
3840 // evaluated in order within a statement or larger expression. This
3841 // is used to implement the rules about order of evaluation.
3843 class Find_eval_ordering
: public Traverse
3846 typedef std::vector
<Expression
**> Expression_pointers
;
3849 Find_eval_ordering()
3850 : Traverse(traverse_blocks
3851 | traverse_statements
3852 | traverse_expressions
),
3858 { return this->exprs_
.size(); }
3860 typedef Expression_pointers::const_iterator const_iterator
;
3864 { return this->exprs_
.begin(); }
3868 { return this->exprs_
.end(); }
3873 { return TRAVERSE_SKIP_COMPONENTS
; }
3876 statement(Block
*, size_t*, Statement
*)
3877 { return TRAVERSE_SKIP_COMPONENTS
; }
3880 expression(Expression
**);
3883 // A list of pointers to expressions with side-effects.
3884 Expression_pointers exprs_
;
3887 // If an expression must be evaluated in order, put it on the list.
3890 Find_eval_ordering::expression(Expression
** expression_pointer
)
3892 Binary_expression
* binexp
= (*expression_pointer
)->binary_expression();
3894 && (binexp
->op() == OPERATOR_ANDAND
|| binexp
->op() == OPERATOR_OROR
))
3896 // Shortcut expressions may potentially have side effects which need
3897 // to be ordered, so add them to the list.
3898 // We don't order its subexpressions here since they may be evaluated
3899 // conditionally. This is handled in remove_shortcuts.
3900 this->exprs_
.push_back(expression_pointer
);
3901 return TRAVERSE_SKIP_COMPONENTS
;
3904 // We have to look at subexpressions before this one.
3905 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3906 return TRAVERSE_EXIT
;
3907 if ((*expression_pointer
)->must_eval_in_order())
3908 this->exprs_
.push_back(expression_pointer
);
3909 return TRAVERSE_SKIP_COMPONENTS
;
3912 // A traversal class for ordering evaluations.
3914 class Order_eval
: public Traverse
3917 Order_eval(Gogo
* gogo
)
3918 : Traverse(traverse_variables
3919 | traverse_statements
),
3924 variable(Named_object
*);
3927 statement(Block
*, size_t*, Statement
*);
3934 // Implement the order of evaluation rules for a statement.
3937 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* stmt
)
3939 // FIXME: This approach doesn't work for switch statements, because
3940 // we add the new statements before the whole switch when we need to
3941 // instead add them just before the switch expression. The right
3942 // fix is probably to lower switch statements with nonconstant cases
3943 // to a series of conditionals.
3944 if (stmt
->switch_statement() != NULL
)
3945 return TRAVERSE_CONTINUE
;
3947 Find_eval_ordering find_eval_ordering
;
3949 // If S is a variable declaration, then ordinary traversal won't do
3950 // anything. We want to explicitly traverse the initialization
3951 // expression if there is one.
3952 Variable_declaration_statement
* vds
= stmt
->variable_declaration_statement();
3953 Expression
* init
= NULL
;
3954 Expression
* orig_init
= NULL
;
3956 stmt
->traverse_contents(&find_eval_ordering
);
3959 init
= vds
->var()->var_value()->init();
3961 return TRAVERSE_CONTINUE
;
3964 // It might seem that this could be
3965 // init->traverse_subexpressions. Unfortunately that can fail
3968 // newvar, err := call(arg())
3969 // Here newvar will have an init of call result 0 of
3970 // call(arg()). If we only traverse subexpressions, we will
3971 // only find arg(), and we won't bother to move anything out.
3972 // Then we get to the assignment to err, we will traverse the
3973 // whole statement, and this time we will find both call() and
3974 // arg(), and so we will move them out. This will cause them to
3975 // be put into temporary variables before the assignment to err
3976 // but after the declaration of newvar. To avoid that problem,
3977 // we traverse the entire expression here.
3978 Expression::traverse(&init
, &find_eval_ordering
);
3981 size_t c
= find_eval_ordering
.size();
3983 return TRAVERSE_CONTINUE
;
3985 // If there is only one expression with a side-effect, we can
3986 // usually leave it in place.
3989 switch (stmt
->classification())
3991 case Statement::STATEMENT_ASSIGNMENT
:
3992 // For an assignment statement, we need to evaluate an
3993 // expression on the right hand side before we evaluate any
3994 // index expression on the left hand side, so for that case
3995 // we always move the expression. Otherwise we mishandle
3996 // m[0] = len(m) where m is a map.
3999 case Statement::STATEMENT_EXPRESSION
:
4001 // If this is a call statement that doesn't return any
4002 // values, it will not have been counted as a value to
4003 // move. We need to move any subexpressions in case they
4004 // are themselves call statements that require passing a
4006 Expression
* expr
= stmt
->expression_statement()->expr();
4007 if (expr
->call_expression() != NULL
4008 && expr
->call_expression()->result_count() == 0)
4010 return TRAVERSE_CONTINUE
;
4014 // We can leave the expression in place.
4015 return TRAVERSE_CONTINUE
;
4019 bool is_thunk
= stmt
->thunk_statement() != NULL
;
4020 Expression_statement
* es
= stmt
->expression_statement();
4021 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4022 p
!= find_eval_ordering
.end();
4025 Expression
** pexpr
= *p
;
4027 // The last expression in a thunk will be the call passed to go
4028 // or defer, which we must not evaluate early.
4029 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
4032 Location loc
= (*pexpr
)->location();
4034 if ((*pexpr
)->call_expression() == NULL
4035 || (*pexpr
)->call_expression()->result_count() < 2)
4037 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4040 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4044 // A call expression which returns multiple results needs to
4045 // be handled specially. We can't create a temporary
4046 // because there is no type to give it. Any actual uses of
4047 // the values will be done via Call_result_expressions.
4049 // Since a given call expression can be shared by multiple
4050 // Call_result_expressions, avoid hoisting the call the
4051 // second time we see it here. In addition, don't try to
4052 // hoist the top-level multi-return call in the statement,
4053 // since doing this would result a tree with more than one copy
4055 if (this->remember_expression(*pexpr
))
4057 else if (es
!= NULL
&& *pexpr
== es
->expr())
4060 s
= Statement::make_statement(*pexpr
, true);
4065 block
->insert_statement_before(*pindex
, s
);
4070 if (init
!= orig_init
)
4071 vds
->var()->var_value()->set_init(init
);
4073 return TRAVERSE_CONTINUE
;
4076 // Implement the order of evaluation rules for the initializer of a
4080 Order_eval::variable(Named_object
* no
)
4082 if (no
->is_result_variable())
4083 return TRAVERSE_CONTINUE
;
4084 Variable
* var
= no
->var_value();
4085 Expression
* init
= var
->init();
4086 if (!var
->is_global() || init
== NULL
)
4087 return TRAVERSE_CONTINUE
;
4089 Find_eval_ordering find_eval_ordering
;
4090 Expression::traverse(&init
, &find_eval_ordering
);
4092 if (find_eval_ordering
.size() <= 1)
4094 // If there is only one expression with a side-effect, we can
4095 // leave it in place.
4096 return TRAVERSE_SKIP_COMPONENTS
;
4099 Expression
* orig_init
= init
;
4101 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4102 p
!= find_eval_ordering
.end();
4105 Expression
** pexpr
= *p
;
4106 Location loc
= (*pexpr
)->location();
4108 if ((*pexpr
)->call_expression() == NULL
4109 || (*pexpr
)->call_expression()->result_count() < 2)
4111 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4114 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4118 // A call expression which returns multiple results needs to
4119 // be handled specially.
4120 s
= Statement::make_statement(*pexpr
, true);
4122 var
->add_preinit_statement(this->gogo_
, s
);
4125 if (init
!= orig_init
)
4126 var
->set_init(init
);
4128 return TRAVERSE_SKIP_COMPONENTS
;
4131 // Use temporary variables to implement the order of evaluation rules.
4134 Gogo::order_evaluations()
4136 Order_eval
order_eval(this);
4137 this->traverse(&order_eval
);
4140 // Order evaluations in a block.
4143 Gogo::order_block(Block
* block
)
4145 Order_eval
order_eval(this);
4146 block
->traverse(&order_eval
);
4149 // A traversal class used to find a single shortcut operator within an
4152 class Find_shortcut
: public Traverse
4156 : Traverse(traverse_blocks
4157 | traverse_statements
4158 | traverse_expressions
),
4162 // A pointer to the expression which was found, or NULL if none was
4166 { return this->found_
; }
4171 { return TRAVERSE_SKIP_COMPONENTS
; }
4174 statement(Block
*, size_t*, Statement
*)
4175 { return TRAVERSE_SKIP_COMPONENTS
; }
4178 expression(Expression
**);
4181 Expression
** found_
;
4184 // Find a shortcut expression.
4187 Find_shortcut::expression(Expression
** pexpr
)
4189 Expression
* expr
= *pexpr
;
4190 Binary_expression
* be
= expr
->binary_expression();
4192 return TRAVERSE_CONTINUE
;
4193 Operator op
= be
->op();
4194 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
4195 return TRAVERSE_CONTINUE
;
4196 go_assert(this->found_
== NULL
);
4197 this->found_
= pexpr
;
4198 return TRAVERSE_EXIT
;
4201 // A traversal class used to turn shortcut operators into explicit if
4204 class Shortcuts
: public Traverse
4207 Shortcuts(Gogo
* gogo
)
4208 : Traverse(traverse_variables
4209 | traverse_statements
),
4215 variable(Named_object
*);
4218 statement(Block
*, size_t*, Statement
*);
4221 // Convert a shortcut operator.
4223 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
4229 // Remove shortcut operators in a single statement.
4232 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
4234 // FIXME: This approach doesn't work for switch statements, because
4235 // we add the new statements before the whole switch when we need to
4236 // instead add them just before the switch expression. The right
4237 // fix is probably to lower switch statements with nonconstant cases
4238 // to a series of conditionals.
4239 if (s
->switch_statement() != NULL
)
4240 return TRAVERSE_CONTINUE
;
4244 Find_shortcut find_shortcut
;
4246 // If S is a variable declaration, then ordinary traversal won't
4247 // do anything. We want to explicitly traverse the
4248 // initialization expression if there is one.
4249 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
4250 Expression
* init
= NULL
;
4252 s
->traverse_contents(&find_shortcut
);
4255 init
= vds
->var()->var_value()->init();
4257 return TRAVERSE_CONTINUE
;
4258 init
->traverse(&init
, &find_shortcut
);
4260 Expression
** pshortcut
= find_shortcut
.found();
4261 if (pshortcut
== NULL
)
4262 return TRAVERSE_CONTINUE
;
4264 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
4265 block
->insert_statement_before(*pindex
, snew
);
4268 if (pshortcut
== &init
)
4269 vds
->var()->var_value()->set_init(init
);
4273 // Remove shortcut operators in the initializer of a global variable.
4276 Shortcuts::variable(Named_object
* no
)
4278 if (no
->is_result_variable())
4279 return TRAVERSE_CONTINUE
;
4280 Variable
* var
= no
->var_value();
4281 Expression
* init
= var
->init();
4282 if (!var
->is_global() || init
== NULL
)
4283 return TRAVERSE_CONTINUE
;
4287 Find_shortcut find_shortcut
;
4288 init
->traverse(&init
, &find_shortcut
);
4289 Expression
** pshortcut
= find_shortcut
.found();
4290 if (pshortcut
== NULL
)
4291 return TRAVERSE_CONTINUE
;
4293 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
4294 var
->add_preinit_statement(this->gogo_
, snew
);
4295 if (pshortcut
== &init
)
4296 var
->set_init(init
);
4300 // Given an expression which uses a shortcut operator, return a
4301 // statement which implements it, and update *PSHORTCUT accordingly.
4304 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
4306 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
4307 Expression
* left
= shortcut
->left();
4308 Expression
* right
= shortcut
->right();
4309 Location loc
= shortcut
->location();
4311 Block
* retblock
= new Block(enclosing
, loc
);
4312 retblock
->set_end_location(loc
);
4314 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
4316 retblock
->add_statement(ts
);
4318 Block
* block
= new Block(retblock
, loc
);
4319 block
->set_end_location(loc
);
4320 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
4321 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
4322 block
->add_statement(assign
);
4324 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
4325 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
4326 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
4328 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
4330 retblock
->add_statement(if_statement
);
4332 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
4336 // Now convert any shortcut operators in LEFT and RIGHT.
4337 // LEFT and RIGHT were skipped in the top level
4338 // Gogo::order_evaluations. We need to order their
4339 // components first.
4340 Order_eval
order_eval(this->gogo_
);
4341 retblock
->traverse(&order_eval
);
4342 Shortcuts
shortcuts(this->gogo_
);
4343 retblock
->traverse(&shortcuts
);
4345 return Statement::make_block_statement(retblock
, loc
);
4348 // Turn shortcut operators into explicit if statements. Doing this
4349 // considerably simplifies the order of evaluation rules.
4352 Gogo::remove_shortcuts()
4354 Shortcuts
shortcuts(this);
4355 this->traverse(&shortcuts
);
4358 // Turn shortcut operators into explicit if statements in a block.
4361 Gogo::remove_shortcuts_in_block(Block
* block
)
4363 Shortcuts
shortcuts(this);
4364 block
->traverse(&shortcuts
);
4367 // Traversal to flatten parse tree after order of evaluation rules are applied.
4369 class Flatten
: public Traverse
4372 Flatten(Gogo
* gogo
, Named_object
* function
)
4373 : Traverse(traverse_variables
4374 | traverse_functions
4375 | traverse_statements
4376 | traverse_expressions
),
4377 gogo_(gogo
), function_(function
), inserter_()
4381 set_inserter(const Statement_inserter
* inserter
)
4382 { this->inserter_
= *inserter
; }
4385 variable(Named_object
*);
4388 function(Named_object
*);
4391 statement(Block
*, size_t* pindex
, Statement
*);
4394 expression(Expression
**);
4399 // The function we are traversing.
4400 Named_object
* function_
;
4401 // Current statement inserter for use by expressions.
4402 Statement_inserter inserter_
;
4405 // Flatten variables.
4408 Flatten::variable(Named_object
* no
)
4410 if (!no
->is_variable())
4411 return TRAVERSE_CONTINUE
;
4413 if (no
->is_variable() && no
->var_value()->is_global())
4415 // Global variables can have loops in their initialization
4416 // expressions. This is handled in flatten_init_expression.
4417 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
4419 return TRAVERSE_CONTINUE
;
4422 if (!no
->var_value()->is_parameter()
4423 && !no
->var_value()->is_receiver()
4424 && !no
->var_value()->is_closure()
4425 && no
->var_value()->is_non_escaping_address_taken()
4426 && !no
->var_value()->is_in_heap()
4427 && no
->var_value()->toplevel_decl() == NULL
)
4429 // Local variable that has address taken but not escape.
4430 // It needs to be live beyond its lexical scope. So we
4431 // create a top-level declaration for it.
4432 // No need to do it if it is already in the top level.
4433 Block
* top_block
= function_
->func_value()->block();
4434 if (top_block
->bindings()->lookup_local(no
->name()) != no
)
4436 Variable
* var
= no
->var_value();
4437 Temporary_statement
* ts
=
4438 Statement::make_temporary(var
->type(), NULL
, var
->location());
4439 ts
->set_is_address_taken();
4440 top_block
->add_statement_at_front(ts
);
4441 var
->set_toplevel_decl(ts
);
4445 go_assert(!no
->var_value()->has_pre_init());
4447 return TRAVERSE_SKIP_COMPONENTS
;
4450 // Flatten the body of a function. Record the function while flattening it,
4451 // so that we can pass it down when flattening an expression.
4454 Flatten::function(Named_object
* no
)
4456 go_assert(this->function_
== NULL
);
4457 this->function_
= no
;
4458 int t
= no
->func_value()->traverse(this);
4459 this->function_
= NULL
;
4461 if (t
== TRAVERSE_EXIT
)
4463 return TRAVERSE_SKIP_COMPONENTS
;
4466 // Flatten statement parse trees.
4469 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
4471 // Because we explicitly traverse the statement's contents
4472 // ourselves, we want to skip block statements here. There is
4473 // nothing to flatten in a block statement.
4474 if (sorig
->is_block_statement())
4475 return TRAVERSE_CONTINUE
;
4477 Statement_inserter
hold_inserter(this->inserter_
);
4478 this->inserter_
= Statement_inserter(block
, pindex
);
4480 // Flatten the expressions first.
4481 int t
= sorig
->traverse_contents(this);
4482 if (t
== TRAVERSE_EXIT
)
4484 this->inserter_
= hold_inserter
;
4488 // Keep flattening until nothing changes.
4489 Statement
* s
= sorig
;
4492 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
4497 t
= s
->traverse_contents(this);
4498 if (t
== TRAVERSE_EXIT
)
4500 this->inserter_
= hold_inserter
;
4506 block
->replace_statement(*pindex
, s
);
4508 this->inserter_
= hold_inserter
;
4509 return TRAVERSE_SKIP_COMPONENTS
;
4512 // Flatten expression parse trees.
4515 Flatten::expression(Expression
** pexpr
)
4517 // Keep flattening until nothing changes.
4520 Expression
* e
= *pexpr
;
4521 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
4522 return TRAVERSE_EXIT
;
4524 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
4530 return TRAVERSE_SKIP_COMPONENTS
;
4536 Gogo::flatten_block(Named_object
* function
, Block
* block
)
4538 Flatten
flatten(this, function
);
4539 block
->traverse(&flatten
);
4542 // Flatten an expression. INSERTER may be NULL, in which case the
4543 // expression had better not need to create any temporaries.
4546 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
4549 Flatten
flatten(this, function
);
4550 if (inserter
!= NULL
)
4551 flatten
.set_inserter(inserter
);
4552 flatten
.expression(pexpr
);
4558 Flatten
flatten(this, NULL
);
4559 this->traverse(&flatten
);
4562 // Traversal to convert calls to the predeclared recover function to
4563 // pass in an argument indicating whether it can recover from a panic
4566 class Convert_recover
: public Traverse
4569 Convert_recover(Named_object
* arg
)
4570 : Traverse(traverse_expressions
),
4576 expression(Expression
**);
4579 // The argument to pass to the function.
4583 // Convert calls to recover.
4586 Convert_recover::expression(Expression
** pp
)
4588 Call_expression
* ce
= (*pp
)->call_expression();
4589 if (ce
!= NULL
&& ce
->is_recover_call())
4590 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
4592 return TRAVERSE_CONTINUE
;
4595 // Traversal for build_recover_thunks.
4597 class Build_recover_thunks
: public Traverse
4600 Build_recover_thunks(Gogo
* gogo
)
4601 : Traverse(traverse_functions
),
4606 function(Named_object
*);
4610 can_recover_arg(Location
);
4616 // If this function calls recover, turn it into a thunk.
4619 Build_recover_thunks::function(Named_object
* orig_no
)
4621 Function
* orig_func
= orig_no
->func_value();
4622 if (!orig_func
->calls_recover()
4623 || orig_func
->is_recover_thunk()
4624 || orig_func
->has_recover_thunk())
4625 return TRAVERSE_CONTINUE
;
4627 Gogo
* gogo
= this->gogo_
;
4628 Location location
= orig_func
->location();
4633 Function_type
* orig_fntype
= orig_func
->type();
4634 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4635 std::string receiver_name
;
4636 if (orig_fntype
->is_method())
4638 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4639 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4641 receiver_name
= buf
;
4642 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4643 receiver
->location()));
4645 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4646 if (orig_params
!= NULL
&& !orig_params
->empty())
4648 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4649 p
!= orig_params
->end();
4652 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4654 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4658 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4660 std::string can_recover_name
= buf
;
4661 new_params
->push_back(Typed_identifier(can_recover_name
,
4662 Type::lookup_bool_type(),
4663 orig_fntype
->location()));
4665 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4666 Typed_identifier_list
* new_results
;
4667 if (orig_results
== NULL
|| orig_results
->empty())
4671 new_results
= new Typed_identifier_list();
4672 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4673 p
!= orig_results
->end();
4675 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4678 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4680 orig_fntype
->location());
4681 if (orig_fntype
->is_varargs())
4682 new_fntype
->set_is_varargs();
4685 if (orig_fntype
->is_method())
4686 rtype
= orig_fntype
->receiver()->type();
4687 std::string
name(gogo
->recover_thunk_name(orig_no
->name(), rtype
));
4688 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4690 Function
*new_func
= new_no
->func_value();
4691 if (orig_func
->enclosing() != NULL
)
4692 new_func
->set_enclosing(orig_func
->enclosing());
4694 // We build the code for the original function attached to the new
4695 // function, and then swap the original and new function bodies.
4696 // This means that existing references to the original function will
4697 // then refer to the new function. That makes this code a little
4698 // confusing, in that the reference to NEW_NO really refers to the
4699 // other function, not the one we are building.
4701 Expression
* closure
= NULL
;
4702 if (orig_func
->needs_closure())
4704 // For the new function we are creating, declare a new parameter
4705 // variable NEW_CLOSURE_NO and set it to be the closure variable
4706 // of the function. This will be set to the closure value
4707 // passed in by the caller. Then pass a reference to this
4708 // variable as the closure value when calling the original
4709 // function. In other words, simply pass the closure value
4710 // through the thunk we are creating.
4711 Named_object
* orig_closure_no
= orig_func
->closure_var();
4712 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4713 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4714 false, false, location
);
4715 new_var
->set_is_closure();
4716 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4718 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4720 new_func
->set_closure_var(new_closure_no
);
4721 closure
= Expression::make_var_reference(new_closure_no
, location
);
4724 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4726 Expression_list
* args
= new Expression_list();
4727 if (new_params
!= NULL
)
4729 // Note that we skip the last parameter, which is the boolean
4730 // indicating whether recover can succed.
4731 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4732 p
+ 1 != new_params
->end();
4735 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4736 go_assert(p_no
!= NULL
4737 && p_no
->is_variable()
4738 && p_no
->var_value()->is_parameter());
4739 args
->push_back(Expression::make_var_reference(p_no
, location
));
4742 args
->push_back(this->can_recover_arg(location
));
4744 gogo
->start_block(location
);
4746 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4748 // Any varargs call has already been lowered.
4749 call
->set_varargs_are_lowered();
4751 Statement
* s
= Statement::make_return_from_call(call
, location
);
4752 s
->determine_types();
4753 gogo
->add_statement(s
);
4755 Block
* b
= gogo
->finish_block(location
);
4757 gogo
->add_block(b
, location
);
4759 // Lower the call in case it returns multiple results.
4760 gogo
->lower_block(new_no
, b
);
4762 gogo
->finish_function(location
);
4764 // Swap the function bodies and types.
4765 new_func
->swap_for_recover(orig_func
);
4766 orig_func
->set_is_recover_thunk();
4767 new_func
->set_calls_recover();
4768 new_func
->set_has_recover_thunk();
4770 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4771 Bindings
* new_bindings
= new_func
->block()->bindings();
4772 if (orig_fntype
->is_method())
4774 // We changed the receiver to be a regular parameter. We have
4775 // to update the binding accordingly in both functions.
4776 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4777 go_assert(orig_rec_no
!= NULL
4778 && orig_rec_no
->is_variable()
4779 && !orig_rec_no
->var_value()->is_receiver());
4780 orig_rec_no
->var_value()->set_is_receiver();
4782 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4783 if (new_receiver_name
.empty())
4785 // Find the receiver. It was named "r.NNN" in
4786 // Gogo::start_function.
4787 for (Bindings::const_definitions_iterator p
=
4788 new_bindings
->begin_definitions();
4789 p
!= new_bindings
->end_definitions();
4792 const std::string
& pname((*p
)->name());
4793 if (pname
[0] == 'r' && pname
[1] == '.')
4795 new_receiver_name
= pname
;
4799 go_assert(!new_receiver_name
.empty());
4801 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4802 if (new_rec_no
== NULL
)
4803 go_assert(saw_errors());
4806 go_assert(new_rec_no
->is_variable()
4807 && new_rec_no
->var_value()->is_receiver());
4808 new_rec_no
->var_value()->set_is_not_receiver();
4812 // Because we flipped blocks but not types, the can_recover
4813 // parameter appears in the (now) old bindings as a parameter.
4814 // Change it to a local variable, whereupon it will be discarded.
4815 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4816 go_assert(can_recover_no
!= NULL
4817 && can_recover_no
->is_variable()
4818 && can_recover_no
->var_value()->is_parameter());
4819 orig_bindings
->remove_binding(can_recover_no
);
4821 // Add the can_recover argument to the (now) new bindings, and
4822 // attach it to any recover statements.
4823 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4824 false, true, false, location
);
4825 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4827 Convert_recover
convert_recover(can_recover_no
);
4828 new_func
->traverse(&convert_recover
);
4830 // Update the function pointers in any named results.
4831 new_func
->update_result_variables();
4832 orig_func
->update_result_variables();
4834 return TRAVERSE_CONTINUE
;
4837 // Return the expression to pass for the .can_recover parameter to the
4838 // new function. This indicates whether a call to recover may return
4839 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4842 Build_recover_thunks::can_recover_arg(Location location
)
4844 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
4845 static Named_object
* can_recover
;
4846 if (can_recover
== NULL
)
4848 const Location bloc
= Linemap::predeclared_location();
4849 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4850 param_types
->push_back(Typed_identifier("a", uintptr_type
, bloc
));
4851 Type
* boolean_type
= Type::lookup_bool_type();
4852 Typed_identifier_list
* results
= new Typed_identifier_list();
4853 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4854 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4857 Named_object::make_function_declaration("runtime_canrecover",
4858 NULL
, fntype
, bloc
);
4859 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4862 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4863 Expression
* call
= Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS
,
4864 location
, 1, zexpr
);
4865 call
= Expression::make_unsafe_cast(uintptr_type
, call
, location
);
4867 Expression_list
* args
= new Expression_list();
4868 args
->push_back(call
);
4870 Expression
* fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4871 return Expression::make_call(fn
, args
, false, location
);
4874 // Build thunks for functions which call recover. We build a new
4875 // function with an extra parameter, which is whether a call to
4876 // recover can succeed. We then move the body of this function to
4877 // that one. We then turn this function into a thunk which calls the
4878 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4879 // The function will be marked as not splitting the stack. This will
4880 // cooperate with the implementation of defer to make recover do the
4884 Gogo::build_recover_thunks()
4886 Build_recover_thunks
build_recover_thunks(this);
4887 this->traverse(&build_recover_thunks
);
4890 // Look for named types to see whether we need to create an interface
4893 class Build_method_tables
: public Traverse
4896 Build_method_tables(Gogo
* gogo
,
4897 const std::vector
<Interface_type
*>& interfaces
)
4898 : Traverse(traverse_types
),
4899 gogo_(gogo
), interfaces_(interfaces
)
4908 // A list of locally defined interfaces which have hidden methods.
4909 const std::vector
<Interface_type
*>& interfaces_
;
4912 // Build all required interface method tables for types. We need to
4913 // ensure that we have an interface method table for every interface
4914 // which has a hidden method, for every named type which implements
4915 // that interface. Normally we can just build interface method tables
4916 // as we need them. However, in some cases we can require an
4917 // interface method table for an interface defined in a different
4918 // package for a type defined in that package. If that interface and
4919 // type both use a hidden method, that is OK. However, we will not be
4920 // able to build that interface method table when we need it, because
4921 // the type's hidden method will be static. So we have to build it
4922 // here, and just refer it from other packages as needed.
4925 Gogo::build_interface_method_tables()
4930 std::vector
<Interface_type
*> hidden_interfaces
;
4931 hidden_interfaces
.reserve(this->interface_types_
.size());
4932 for (std::vector
<Interface_type
*>::const_iterator pi
=
4933 this->interface_types_
.begin();
4934 pi
!= this->interface_types_
.end();
4937 const Typed_identifier_list
* methods
= (*pi
)->methods();
4938 if (methods
== NULL
)
4940 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4941 pm
!= methods
->end();
4944 if (Gogo::is_hidden_name(pm
->name()))
4946 hidden_interfaces
.push_back(*pi
);
4952 if (!hidden_interfaces
.empty())
4954 // Now traverse the tree looking for all named types.
4955 Build_method_tables
bmt(this, hidden_interfaces
);
4956 this->traverse(&bmt
);
4959 // We no longer need the list of interfaces.
4961 this->interface_types_
.clear();
4964 // This is called for each type. For a named type, for each of the
4965 // interfaces with hidden methods that it implements, create the
4969 Build_method_tables::type(Type
* type
)
4971 Named_type
* nt
= type
->named_type();
4972 Struct_type
* st
= type
->struct_type();
4973 if (nt
!= NULL
|| st
!= NULL
)
4975 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4976 for (std::vector
<Interface_type
*>::const_iterator p
=
4977 this->interfaces_
.begin();
4978 p
!= this->interfaces_
.end();
4981 // We ask whether a pointer to the named type implements the
4982 // interface, because a pointer can implement more methods
4986 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4989 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4990 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4995 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4998 st
->interface_method_table(*p
, false)->get_backend(&context
);
4999 st
->interface_method_table(*p
, true)->get_backend(&context
);
5004 return TRAVERSE_CONTINUE
;
5007 // Return an expression which allocates memory to hold values of type TYPE.
5010 Gogo::allocate_memory(Type
* type
, Location location
)
5012 Expression
* td
= Expression::make_type_descriptor(type
, location
);
5013 return Runtime::make_call(Runtime::NEW
, location
, 1, td
);
5016 // Traversal class used to check for return statements.
5018 class Check_return_statements_traverse
: public Traverse
5021 Check_return_statements_traverse()
5022 : Traverse(traverse_functions
)
5026 function(Named_object
*);
5029 // Check that a function has a return statement if it needs one.
5032 Check_return_statements_traverse::function(Named_object
* no
)
5034 Function
* func
= no
->func_value();
5035 const Function_type
* fntype
= func
->type();
5036 const Typed_identifier_list
* results
= fntype
->results();
5038 // We only need a return statement if there is a return value.
5039 if (results
== NULL
|| results
->empty())
5040 return TRAVERSE_CONTINUE
;
5042 if (func
->block()->may_fall_through())
5043 go_error_at(func
->block()->end_location(),
5044 "missing return at end of function");
5046 return TRAVERSE_CONTINUE
;
5049 // Check return statements.
5052 Gogo::check_return_statements()
5054 Check_return_statements_traverse traverse
;
5055 this->traverse(&traverse
);
5058 // Traversal class to decide whether a function body is less than the
5059 // inlining budget. This adjusts *available as it goes, and stops the
5060 // traversal if it goes negative.
5062 class Inline_within_budget
: public Traverse
5065 Inline_within_budget(int* available
)
5066 : Traverse(traverse_statements
5067 | traverse_expressions
),
5068 available_(available
)
5072 statement(Block
*, size_t*, Statement
*);
5075 expression(Expression
**);
5078 // Pointer to remaining budget.
5082 // Adjust the budget for the inlining cost of a statement.
5085 Inline_within_budget::statement(Block
*, size_t*, Statement
* s
)
5087 if (*this->available_
< 0)
5088 return TRAVERSE_EXIT
;
5089 *this->available_
-= s
->inlining_cost();
5090 return TRAVERSE_CONTINUE
;
5093 // Adjust the budget for the inlining cost of an expression.
5096 Inline_within_budget::expression(Expression
** pexpr
)
5098 if (*this->available_
< 0)
5099 return TRAVERSE_EXIT
;
5100 *this->available_
-= (*pexpr
)->inlining_cost();
5101 return TRAVERSE_CONTINUE
;
5104 // Traversal class to find functions whose body should be exported for
5105 // inlining by other packages.
5107 class Mark_inline_candidates
: public Traverse
5110 Mark_inline_candidates(Unordered_set(Named_object
*)* marked
)
5111 : Traverse(traverse_functions
5113 marked_functions_(marked
)
5117 function(Named_object
*);
5123 // We traverse the function body trying to determine how expensive
5124 // it is for inlining. We start with a budget, and decrease that
5125 // budget for each statement and expression. If the budget goes
5126 // negative, we do not export the function body. The value of this
5127 // budget is a heuristic. In the usual GCC spirit, we could
5128 // consider setting this via a command line option.
5129 const int budget_heuristic
= 80;
5131 // Set of named objects that are marked as inline candidates.
5132 Unordered_set(Named_object
*)* marked_functions_
;
5135 // Mark a function if it is an inline candidate.
5138 Mark_inline_candidates::function(Named_object
* no
)
5140 Function
* func
= no
->func_value();
5141 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5142 return TRAVERSE_CONTINUE
;
5143 int budget
= budget_heuristic
;
5144 Inline_within_budget
iwb(&budget
);
5145 func
->block()->traverse(&iwb
);
5148 func
->set_export_for_inlining();
5149 this->marked_functions_
->insert(no
);
5151 return TRAVERSE_CONTINUE
;
5154 // Mark methods if they are inline candidates.
5157 Mark_inline_candidates::type(Type
* t
)
5159 Named_type
* nt
= t
->named_type();
5160 if (nt
== NULL
|| nt
->is_alias())
5161 return TRAVERSE_CONTINUE
;
5162 const Bindings
* methods
= nt
->local_methods();
5163 if (methods
== NULL
)
5164 return TRAVERSE_CONTINUE
;
5165 for (Bindings::const_definitions_iterator p
= methods
->begin_definitions();
5166 p
!= methods
->end_definitions();
5169 Named_object
* no
= *p
;
5170 go_assert(no
->is_function());
5171 Function
*func
= no
->func_value();
5172 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5174 int budget
= budget_heuristic
;
5175 Inline_within_budget
iwb(&budget
);
5176 func
->block()->traverse(&iwb
);
5179 func
->set_export_for_inlining();
5180 this->marked_functions_
->insert(no
);
5183 return TRAVERSE_CONTINUE
;
5186 // Export identifiers as requested.
5194 // Mark any functions whose body should be exported for inlining by
5196 Unordered_set(Named_object
*) marked_functions
;
5197 Mark_inline_candidates
mic(&marked_functions
);
5198 this->traverse(&mic
);
5200 // For now we always stream to a section. Later we may want to
5201 // support streaming to a separate file.
5202 Stream_to_section
stream(this->backend());
5204 // Write out either the prefix or pkgpath depending on how we were
5207 std::string pkgpath
;
5208 if (this->pkgpath_from_option_
)
5209 pkgpath
= this->pkgpath_
;
5210 else if (this->prefix_from_option_
)
5211 prefix
= this->prefix_
;
5212 else if (this->is_main_package())
5217 std::string init_fn_name
;
5218 if (this->is_main_package())
5220 else if (this->need_init_fn_
)
5221 init_fn_name
= this->get_init_fn_name();
5223 init_fn_name
= this->dummy_init_fn_name();
5225 Export
exp(&stream
);
5226 exp
.register_builtin_types(this);
5227 exp
.export_globals(this->package_name(),
5233 this->imported_init_fns_
,
5234 this->package_
->bindings(),
5237 if (!this->c_header_
.empty() && !saw_errors())
5238 this->write_c_header();
5241 // Write the top level named struct types in C format to a C header
5242 // file. This is used when building the runtime package, to share
5243 // struct definitions between C and Go.
5246 Gogo::write_c_header()
5249 out
.open(this->c_header_
.c_str());
5252 go_error_at(Linemap::unknown_location(),
5253 "cannot open %s: %m", this->c_header_
.c_str());
5257 std::list
<Named_object
*> types
;
5258 Bindings
* top
= this->package_
->bindings();
5259 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
5260 p
!= top
->end_definitions();
5263 Named_object
* no
= *p
;
5265 // Skip names that start with underscore followed by something
5266 // other than an uppercase letter, as when compiling the runtime
5267 // package they are mostly types defined by mkrsysinfo.sh based
5268 // on the C system header files. We don't need to translate
5269 // types to C and back to Go. But do accept the special cases
5270 // _defer, _panic, and _type.
5271 std::string name
= Gogo::unpack_hidden_name(no
->name());
5273 && (name
[1] < 'A' || name
[1] > 'Z')
5274 && (name
!= "_defer" && name
!= "_panic" && name
!= "_type"))
5277 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
5278 types
.push_back(no
);
5280 && no
->const_value()->type()->integer_type() != NULL
5281 && !no
->const_value()->is_sink())
5283 Numeric_constant nc
;
5285 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
5286 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
5288 out
<< "#define " << no
->message_name() << ' ' << val
5294 std::vector
<const Named_object
*> written
;
5296 while (!types
.empty())
5298 Named_object
* no
= types
.front();
5301 std::vector
<const Named_object
*> requires
;
5302 std::vector
<const Named_object
*> declare
;
5303 if (!no
->type_value()->struct_type()->can_write_to_c_header(&requires
,
5308 for (std::vector
<const Named_object
*>::const_iterator pr
5310 pr
!= requires
.end() && ok
;
5313 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
5314 pt
!= types
.end() && ok
;
5324 // This should be impossible since the code parsed and
5329 types
.push_back(no
);
5333 for (std::vector
<const Named_object
*>::const_iterator pd
5335 pd
!= declare
.end();
5341 std::vector
<const Named_object
*> drequires
;
5342 std::vector
<const Named_object
*> ddeclare
;
5343 if (!(*pd
)->type_value()->struct_type()->
5344 can_write_to_c_header(&drequires
, &ddeclare
))
5348 for (std::vector
<const Named_object
*>::const_iterator pw
5350 pw
!= written
.end();
5362 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
5363 written
.push_back(*pd
);
5368 out
<< "struct " << no
->message_name() << " {" << std::endl
;
5369 no
->type_value()->struct_type()->write_to_c_header(out
);
5370 out
<< "};" << std::endl
;
5371 written
.push_back(no
);
5376 go_error_at(Linemap::unknown_location(),
5377 "error writing to %s: %m", this->c_header_
.c_str());
5380 // Find the blocks in order to convert named types defined in blocks.
5382 class Convert_named_types
: public Traverse
5385 Convert_named_types(Gogo
* gogo
)
5386 : Traverse(traverse_blocks
),
5392 block(Block
* block
);
5399 Convert_named_types::block(Block
* block
)
5401 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
5402 return TRAVERSE_CONTINUE
;
5405 // Convert all named types to the backend representation. Since named
5406 // types can refer to other types, this needs to be done in the right
5407 // sequence, which is handled by Named_type::convert. Here we arrange
5408 // to call that for each named type.
5411 Gogo::convert_named_types()
5413 this->convert_named_types_in_bindings(this->globals_
);
5414 for (Packages::iterator p
= this->packages_
.begin();
5415 p
!= this->packages_
.end();
5418 Package
* package
= p
->second
;
5419 this->convert_named_types_in_bindings(package
->bindings());
5422 Convert_named_types
cnt(this);
5423 this->traverse(&cnt
);
5425 // Make all the builtin named types used for type descriptors, and
5426 // then convert them. They will only be written out if they are
5428 Type::make_type_descriptor_type();
5429 Type::make_type_descriptor_ptr_type();
5430 Function_type::make_function_type_descriptor_type();
5431 Pointer_type::make_pointer_type_descriptor_type();
5432 Struct_type::make_struct_type_descriptor_type();
5433 Array_type::make_array_type_descriptor_type();
5434 Array_type::make_slice_type_descriptor_type();
5435 Map_type::make_map_type_descriptor_type();
5436 Channel_type::make_chan_type_descriptor_type();
5437 Interface_type::make_interface_type_descriptor_type();
5438 Expression::make_func_descriptor_type();
5439 Type::convert_builtin_named_types(this);
5441 Runtime::convert_types(this);
5443 this->named_types_are_converted_
= true;
5445 Type::finish_pointer_types(this);
5448 // Convert all names types in a set of bindings.
5451 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
5453 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
5454 p
!= bindings
->end_definitions();
5457 if ((*p
)->is_type())
5458 (*p
)->type_value()->convert(this);
5463 debug_go_gogo(Gogo
* gogo
)
5472 std::cerr
<< "Packages:\n";
5473 for (Packages::const_iterator p
= this->packages_
.begin();
5474 p
!= this->packages_
.end();
5477 const char *tag
= " ";
5478 if (p
->second
== this->package_
)
5480 std::cerr
<< tag
<< "'" << p
->first
<< "' "
5481 << p
->second
->pkgpath() << " " << ((void*)p
->second
) << "\n";
5487 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
5489 : type_(type
), enclosing_(enclosing
), results_(NULL
),
5490 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
5491 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
5492 pragmas_(0), nested_functions_(0), is_sink_(false),
5493 results_are_named_(false), is_unnamed_type_stub_method_(false),
5494 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5495 calls_defer_retaddr_(false), is_type_specific_function_(false),
5496 in_unique_section_(false), export_for_inlining_(false),
5497 is_inline_only_(false), is_referenced_by_inline_(false),
5498 is_exported_by_linkname_(false)
5502 // Create the named result variables.
5505 Function::create_result_variables(Gogo
* gogo
)
5507 const Typed_identifier_list
* results
= this->type_
->results();
5508 if (results
== NULL
|| results
->empty())
5511 if (!results
->front().name().empty())
5512 this->results_are_named_
= true;
5514 this->results_
= new Results();
5515 this->results_
->reserve(results
->size());
5517 Block
* block
= this->block_
;
5519 for (Typed_identifier_list::const_iterator p
= results
->begin();
5520 p
!= results
->end();
5523 std::string name
= p
->name();
5524 if (name
.empty() || Gogo::is_sink_name(name
))
5526 static int result_counter
;
5528 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
5530 name
= gogo
->pack_hidden_name(buf
, false);
5532 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
5534 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
5535 if (no
->is_result_variable())
5536 this->results_
->push_back(no
);
5539 static int dummy_result_count
;
5541 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
5542 ++dummy_result_count
;
5543 name
= gogo
->pack_hidden_name(buf
, false);
5544 no
= block
->bindings()->add_result_variable(name
, result
);
5545 go_assert(no
->is_result_variable());
5546 this->results_
->push_back(no
);
5551 // Update the named result variables when cloning a function which
5555 Function::update_result_variables()
5557 if (this->results_
== NULL
)
5560 for (Results::iterator p
= this->results_
->begin();
5561 p
!= this->results_
->end();
5563 (*p
)->result_var_value()->set_function(this);
5566 // Whether this method should not be included in the type descriptor.
5569 Function::nointerface() const
5571 go_assert(this->is_method());
5572 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
5575 // Record that this method should not be included in the type
5579 Function::set_nointerface()
5581 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
5584 // Return the closure variable, creating it if necessary.
5587 Function::closure_var()
5589 if (this->closure_var_
== NULL
)
5591 go_assert(this->descriptor_
== NULL
);
5592 // We don't know the type of the variable yet. We add fields as
5594 Location loc
= this->type_
->location();
5595 Struct_field_list
* sfl
= new Struct_field_list
;
5596 Struct_type
* struct_type
= Type::make_struct_type(sfl
, loc
);
5597 struct_type
->set_is_struct_incomparable();
5598 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
5599 NULL
, false, false, false, loc
);
5601 var
->set_is_closure();
5602 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
5603 // Note that the new variable is not in any binding contour.
5605 return this->closure_var_
;
5608 // Set the type of the closure variable.
5611 Function::set_closure_type()
5613 if (this->closure_var_
== NULL
)
5615 Named_object
* closure
= this->closure_var_
;
5616 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
5618 // The first field of a closure is always a pointer to the function
5620 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
5621 st
->push_field(Struct_field(Typed_identifier(".f", voidptr_type
,
5624 unsigned int index
= 1;
5625 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
5626 p
!= this->closure_fields_
.end();
5629 Named_object
* no
= p
->first
;
5631 snprintf(buf
, sizeof buf
, "%u", index
);
5632 std::string n
= no
->name() + buf
;
5634 if (no
->is_variable())
5635 var_type
= no
->var_value()->type();
5637 var_type
= no
->result_var_value()->type();
5638 Type
* field_type
= Type::make_pointer_type(var_type
);
5639 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
5643 // Return whether this function is a method.
5646 Function::is_method() const
5648 return this->type_
->is_method();
5651 // Add a label definition.
5654 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
5657 Label
* lnull
= NULL
;
5658 std::pair
<Labels::iterator
, bool> ins
=
5659 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5661 if (label_name
== "_")
5663 label
= Label::create_dummy_label();
5665 ins
.first
->second
= label
;
5667 else if (ins
.second
)
5669 // This is a new label.
5670 label
= new Label(label_name
);
5671 ins
.first
->second
= label
;
5675 // The label was already in the hash table.
5676 label
= ins
.first
->second
;
5677 if (label
->is_defined())
5679 go_error_at(location
, "label %qs already defined",
5680 Gogo::message_name(label_name
).c_str());
5681 go_inform(label
->location(), "previous definition of %qs was here",
5682 Gogo::message_name(label_name
).c_str());
5683 return new Label(label_name
);
5687 label
->define(location
, gogo
->bindings_snapshot(location
));
5689 // Issue any errors appropriate for any previous goto's to this
5691 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
5692 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
5695 (*p
)->check_goto_to(gogo
->current_block());
5696 label
->clear_refs();
5701 // Add a reference to a label.
5704 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
5705 Location location
, bool issue_goto_errors
)
5707 Label
* lnull
= NULL
;
5708 std::pair
<Labels::iterator
, bool> ins
=
5709 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5713 // The label was already in the hash table.
5714 label
= ins
.first
->second
;
5718 go_assert(ins
.first
->second
== NULL
);
5719 label
= new Label(label_name
);
5720 ins
.first
->second
= label
;
5723 label
->set_is_used();
5725 if (issue_goto_errors
)
5727 Bindings_snapshot
* snapshot
= label
->snapshot();
5728 if (snapshot
!= NULL
)
5729 snapshot
->check_goto_from(gogo
->current_block(), location
);
5731 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
5737 // Warn about labels that are defined but not used.
5740 Function::check_labels() const
5742 for (Labels::const_iterator p
= this->labels_
.begin();
5743 p
!= this->labels_
.end();
5746 Label
* label
= p
->second
;
5747 if (!label
->is_used())
5748 go_error_at(label
->location(), "label %qs defined and not used",
5749 Gogo::message_name(label
->name()).c_str());
5753 // Swap one function with another. This is used when building the
5754 // thunk we use to call a function which calls recover. It may not
5755 // work for any other case.
5758 Function::swap_for_recover(Function
*x
)
5760 go_assert(this->enclosing_
== x
->enclosing_
);
5761 std::swap(this->results_
, x
->results_
);
5762 std::swap(this->closure_var_
, x
->closure_var_
);
5763 std::swap(this->block_
, x
->block_
);
5764 go_assert(this->location_
== x
->location_
);
5765 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
5766 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
5769 // Traverse the tree.
5772 Function::traverse(Traverse
* traverse
)
5774 unsigned int traverse_mask
= traverse
->traverse_mask();
5777 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
5780 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
5781 return TRAVERSE_EXIT
;
5784 // FIXME: We should check traverse_functions here if nested
5785 // functions are stored in block bindings.
5786 if (this->block_
!= NULL
5788 & (Traverse::traverse_variables
5789 | Traverse::traverse_constants
5790 | Traverse::traverse_blocks
5791 | Traverse::traverse_statements
5792 | Traverse::traverse_expressions
5793 | Traverse::traverse_types
)) != 0)
5795 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5796 return TRAVERSE_EXIT
;
5799 return TRAVERSE_CONTINUE
;
5802 // Work out types for unspecified variables and constants.
5805 Function::determine_types()
5807 if (this->block_
!= NULL
)
5808 this->block_
->determine_types();
5811 // Return the function descriptor, the value you get when you refer to
5812 // the function in Go code without calling it.
5815 Function::descriptor(Gogo
*, Named_object
* no
)
5817 go_assert(!this->is_method());
5818 go_assert(this->closure_var_
== NULL
);
5819 if (this->descriptor_
== NULL
)
5820 this->descriptor_
= Expression::make_func_descriptor(no
);
5821 return this->descriptor_
;
5824 // Get a pointer to the variable representing the defer stack for this
5825 // function, making it if necessary. The value of the variable is set
5826 // by the runtime routines to true if the function is returning,
5827 // rather than panicing through. A pointer to this variable is used
5828 // as a marker for the functions on the defer stack associated with
5829 // this function. A function-specific variable permits inlining a
5830 // function which uses defer.
5833 Function::defer_stack(Location location
)
5835 if (this->defer_stack_
== NULL
)
5837 Type
* t
= Type::lookup_bool_type();
5838 Expression
* n
= Expression::make_boolean(false, location
);
5839 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5840 this->defer_stack_
->set_is_address_taken();
5842 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5844 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5847 // Export the function.
5850 Function::export_func(Export
* exp
, const Named_object
* no
) const
5852 Block
* block
= NULL
;
5853 if (this->export_for_inlining())
5854 block
= this->block_
;
5855 Function::export_func_with_type(exp
, no
, this->type_
, this->results_
,
5856 this->is_method() && this->nointerface(),
5857 this->asm_name(), block
, this->location_
);
5860 // Export a function with a type.
5863 Function::export_func_with_type(Export
* exp
, const Named_object
* no
,
5864 const Function_type
* fntype
,
5865 Function::Results
* result_vars
,
5866 bool nointerface
, const std::string
& asm_name
,
5867 Block
* block
, Location loc
)
5869 exp
->write_c_string("func ");
5873 go_assert(fntype
->is_method());
5874 exp
->write_c_string("/*nointerface*/ ");
5877 if (!asm_name
.empty())
5879 exp
->write_c_string("/*asm ");
5880 exp
->write_string(asm_name
);
5881 exp
->write_c_string(" */ ");
5884 if (fntype
->is_method())
5886 exp
->write_c_string("(");
5887 const Typed_identifier
* receiver
= fntype
->receiver();
5888 exp
->write_name(receiver
->name());
5889 exp
->write_escape(receiver
->note());
5890 exp
->write_c_string(" ");
5891 exp
->write_type(receiver
->type());
5892 exp
->write_c_string(") ");
5895 if (no
->package() != NULL
&& !fntype
->is_method())
5898 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
5899 exp
->write_c_string(buf
);
5902 const std::string
& name(no
->name());
5903 if (!Gogo::is_hidden_name(name
))
5904 exp
->write_string(name
);
5907 exp
->write_c_string(".");
5908 exp
->write_string(Gogo::unpack_hidden_name(name
));
5911 exp
->write_c_string(" (");
5912 const Typed_identifier_list
* parameters
= fntype
->parameters();
5913 if (parameters
!= NULL
)
5916 bool is_varargs
= fntype
->is_varargs();
5918 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5919 p
!= parameters
->end();
5925 exp
->write_c_string(", ");
5926 exp
->write_name(p
->name());
5927 exp
->write_escape(p
->note());
5928 exp
->write_c_string(" ");
5929 if (!is_varargs
|| p
+ 1 != parameters
->end())
5930 exp
->write_type(p
->type());
5933 exp
->write_c_string("...");
5934 exp
->write_type(p
->type()->array_type()->element_type());
5938 exp
->write_c_string(")");
5940 const Typed_identifier_list
* result_decls
= fntype
->results();
5941 if (result_decls
!= NULL
)
5943 if (result_decls
->size() == 1
5944 && result_decls
->begin()->name().empty()
5947 exp
->write_c_string(" ");
5948 exp
->write_type(result_decls
->begin()->type());
5952 exp
->write_c_string(" (");
5954 Results::const_iterator pr
;
5955 if (result_vars
!= NULL
)
5956 pr
= result_vars
->begin();
5957 for (Typed_identifier_list::const_iterator pd
= result_decls
->begin();
5958 pd
!= result_decls
->end();
5964 exp
->write_c_string(", ");
5965 // We only use pr->name, which may be artificial, if
5966 // need it for inlining.
5967 if (block
== NULL
|| result_vars
== NULL
)
5968 exp
->write_name(pd
->name());
5970 exp
->write_name((*pr
)->name());
5971 exp
->write_escape(pd
->note());
5972 exp
->write_c_string(" ");
5973 exp
->write_type(pd
->type());
5974 if (result_vars
!= NULL
)
5977 if (result_vars
!= NULL
)
5978 go_assert(pr
== result_vars
->end());
5979 exp
->write_c_string(")");
5984 exp
->write_c_string("\n");
5988 if (fntype
->is_method())
5991 Export_function_body
efb(exp
, indent
);
5994 efb
.write_c_string("// ");
5995 efb
.write_string(Linemap::location_to_file(block
->start_location()));
5996 efb
.write_char(':');
5998 snprintf(buf
, sizeof buf
, "%d", Linemap::location_to_line(loc
));
5999 efb
.write_c_string(buf
);
6000 efb
.write_char('\n');
6001 block
->export_block(&efb
);
6003 const std::string
& body(efb
.body());
6005 snprintf(buf
, sizeof buf
, " <inl:%lu>\n",
6006 static_cast<unsigned long>(body
.length()));
6007 exp
->write_c_string(buf
);
6009 exp
->write_string(body
);
6013 // Import a function.
6016 Function::import_func(Import
* imp
, std::string
* pname
,
6017 Package
** ppkg
, bool* pis_exported
,
6018 Typed_identifier
** preceiver
,
6019 Typed_identifier_list
** pparameters
,
6020 Typed_identifier_list
** presults
,
6023 std::string
* asm_name
,
6026 imp
->require_c_string("func ");
6028 *nointerface
= false;
6029 while (imp
->match_c_string("/*"))
6032 if (imp
->match_c_string("nointerface"))
6034 imp
->require_c_string("nointerface*/ ");
6035 *nointerface
= true;
6037 else if (imp
->match_c_string("asm"))
6039 imp
->require_c_string("asm ");
6040 *asm_name
= imp
->read_identifier();
6041 imp
->require_c_string(" */ ");
6045 go_error_at(imp
->location(),
6046 "import error at %d: unrecognized function comment",
6054 // Only a method can be nointerface.
6055 go_assert(imp
->peek_char() == '(');
6059 if (imp
->peek_char() == '(')
6061 imp
->require_c_string("(");
6062 std::string name
= imp
->read_name();
6063 std::string escape_note
= imp
->read_escape();
6064 imp
->require_c_string(" ");
6065 Type
* rtype
= imp
->read_type();
6066 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
6067 (*preceiver
)->set_note(escape_note
);
6068 imp
->require_c_string(") ");
6071 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
6073 go_error_at(imp
->location(),
6074 "import error at %d: bad function name in export data",
6079 Typed_identifier_list
* parameters
;
6080 *is_varargs
= false;
6081 imp
->require_c_string(" (");
6082 if (imp
->peek_char() == ')')
6086 parameters
= new Typed_identifier_list();
6089 std::string name
= imp
->read_name();
6090 std::string escape_note
= imp
->read_escape();
6091 imp
->require_c_string(" ");
6093 if (imp
->match_c_string("..."))
6099 Type
* ptype
= imp
->read_type();
6101 ptype
= Type::make_array_type(ptype
, NULL
);
6102 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
6103 t
.set_note(escape_note
);
6104 parameters
->push_back(t
);
6105 if (imp
->peek_char() != ',')
6107 go_assert(!*is_varargs
);
6108 imp
->require_c_string(", ");
6111 imp
->require_c_string(")");
6112 *pparameters
= parameters
;
6114 Typed_identifier_list
* results
;
6115 if (imp
->peek_char() != ' ' || imp
->match_c_string(" <inl"))
6119 results
= new Typed_identifier_list();
6120 imp
->require_c_string(" ");
6121 if (imp
->peek_char() != '(')
6123 Type
* rtype
= imp
->read_type();
6124 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
6128 imp
->require_c_string("(");
6131 std::string name
= imp
->read_name();
6132 std::string note
= imp
->read_escape();
6133 imp
->require_c_string(" ");
6134 Type
* rtype
= imp
->read_type();
6135 Typed_identifier t
= Typed_identifier(name
, rtype
,
6138 results
->push_back(t
);
6139 if (imp
->peek_char() != ',')
6141 imp
->require_c_string(", ");
6143 imp
->require_c_string(")");
6146 *presults
= results
;
6148 if (!imp
->match_c_string(" <inl:"))
6150 imp
->require_semicolon_if_old_version();
6151 imp
->require_c_string("\n");
6156 imp
->require_c_string(" <inl:");
6161 c
= imp
->peek_char();
6162 if (c
< '0' || c
> '9')
6167 imp
->require_c_string(">\n");
6171 long llen
= strtol(lenstr
.c_str(), &end
, 10);
6174 || (llen
== LONG_MAX
&& errno
== ERANGE
))
6176 go_error_at(imp
->location(), "invalid inline function length %s",
6181 *body
= imp
->read(static_cast<size_t>(llen
));
6187 // Get the backend representation.
6190 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6192 if (this->fndecl_
== NULL
)
6194 unsigned int flags
= 0;
6195 bool is_init_fn
= false;
6196 if (no
->package() != NULL
)
6198 // Functions defined in other packages must be visible.
6199 flags
|= Backend::function_is_visible
;
6201 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
6203 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
6204 && !this->type_
->is_method())
6206 else if (no
->name() == gogo
->get_init_fn_name())
6208 flags
|= Backend::function_is_visible
;
6211 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
6212 && gogo
->is_main_package())
6213 flags
|= Backend::function_is_visible
;
6214 // Methods have to be public even if they are hidden because
6215 // they can be pulled into type descriptors when using
6216 // anonymous fields.
6217 else if (!Gogo::is_hidden_name(no
->name())
6218 || this->type_
->is_method())
6220 if (!this->is_unnamed_type_stub_method_
)
6221 flags
|= Backend::function_is_visible
;
6225 if (this->type_
->is_method())
6226 rtype
= this->type_
->receiver()->type();
6228 std::string asm_name
;
6229 if (!this->asm_name_
.empty())
6231 asm_name
= this->asm_name_
;
6233 // If an assembler name is explicitly specified, there must
6234 // be some reason to refer to the symbol from a different
6236 flags
|= Backend::function_is_visible
;
6238 else if (is_init_fn
)
6240 // These names appear in the export data and are used
6241 // directly in the assembler code. If we change this here
6242 // we need to change Gogo::init_imports.
6243 asm_name
= no
->name();
6246 asm_name
= gogo
->function_asm_name(no
->name(), no
->package(), rtype
);
6248 // If an inline body refers to this function, then it
6249 // needs to be visible in the symbol table.
6250 if (this->is_referenced_by_inline_
)
6251 flags
|= Backend::function_is_visible
;
6253 // A go:linkname directive can be used to force a function to be
6255 if (this->is_exported_by_linkname_
)
6256 flags
|= Backend::function_is_visible
;
6258 // If a function calls the predeclared recover function, we
6259 // can't inline it, because recover behaves differently in a
6260 // function passed directly to defer. If this is a recover
6261 // thunk that we built to test whether a function can be
6262 // recovered, we can't inline it, because that will mess up
6263 // our return address comparison.
6264 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
6266 // If a function calls __go_set_defer_retaddr, then mark it as
6267 // uninlinable. This prevents the GCC backend from splitting
6268 // the function; splitting the function is a bad idea because we
6269 // want the return address label to be in the same function as
6271 if (this->calls_defer_retaddr_
)
6272 is_inlinable
= false;
6274 // Check the //go:noinline compiler directive.
6275 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
6276 is_inlinable
= false;
6279 flags
|= Backend::function_is_inlinable
;
6281 // If this is a thunk created to call a function which calls
6282 // the predeclared recover function, we need to disable
6283 // stack splitting for the thunk.
6284 bool disable_split_stack
= this->is_recover_thunk_
;
6286 // Check the //go:nosplit compiler directive.
6287 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
6288 disable_split_stack
= true;
6290 if (disable_split_stack
)
6291 flags
|= Backend::function_no_split_stack
;
6293 // This should go into a unique section if that has been
6294 // requested elsewhere, or if this is a nointerface function.
6295 // We want to put a nointerface function into a unique section
6296 // because there is a good chance that the linker garbage
6297 // collection can discard it.
6298 if (this->in_unique_section_
6299 || (this->is_method() && this->nointerface()))
6300 flags
|= Backend::function_in_unique_section
;
6302 if (this->is_inline_only_
)
6303 flags
|= Backend::function_only_inline
;
6305 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
6307 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
6308 flags
, this->location());
6310 return this->fndecl_
;
6313 // Get the backend representation.
6316 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6318 if (this->fndecl_
== NULL
)
6320 unsigned int flags
=
6321 (Backend::function_is_visible
6322 | Backend::function_is_declaration
6323 | Backend::function_is_inlinable
);
6325 // Let Go code use an asm declaration to pick up a builtin
6327 if (!this->asm_name_
.empty())
6329 Bfunction
* builtin_decl
=
6330 gogo
->backend()->lookup_builtin(this->asm_name_
);
6331 if (builtin_decl
!= NULL
)
6333 this->fndecl_
= builtin_decl
;
6334 return this->fndecl_
;
6337 if (this->asm_name_
== "runtime.gopanic"
6338 || this->asm_name_
.compare(0, 13, "runtime.panic") == 0
6339 || this->asm_name_
.compare(0, 15, "runtime.goPanic") == 0
6340 || this->asm_name_
== "runtime.block")
6341 flags
|= Backend::function_does_not_return
;
6344 std::string asm_name
;
6345 if (this->asm_name_
.empty())
6348 if (this->fntype_
->is_method())
6349 rtype
= this->fntype_
->receiver()->type();
6350 asm_name
= gogo
->function_asm_name(no
->name(), no
->package(), rtype
);
6352 else if (go_id_needs_encoding(no
->get_id(gogo
)))
6353 asm_name
= go_encode_id(no
->get_id(gogo
));
6355 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
6357 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
6358 flags
, this->location());
6361 return this->fndecl_
;
6364 // Build the descriptor for a function declaration. This won't
6365 // necessarily happen if the package has just a declaration for the
6366 // function and no other reference to it, but we may still need the
6367 // descriptor for references from other packages.
6369 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
6371 if (this->descriptor_
!= NULL
)
6373 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
6374 this->descriptor_
->get_backend(&context
);
6378 // Check that the types used in this declaration's signature are defined.
6379 // Reports errors for any undefined type.
6382 Function_declaration::check_types() const
6384 // Calling Type::base will give errors for any undefined types.
6385 Function_type
* fntype
= this->type();
6386 if (fntype
->receiver() != NULL
)
6387 fntype
->receiver()->type()->base();
6388 if (fntype
->parameters() != NULL
)
6390 const Typed_identifier_list
* params
= fntype
->parameters();
6391 for (Typed_identifier_list::const_iterator p
= params
->begin();
6398 // Return the function's decl after it has been built.
6401 Function::get_decl() const
6403 go_assert(this->fndecl_
!= NULL
);
6404 return this->fndecl_
;
6407 // Build the backend representation for the function code.
6410 Function::build(Gogo
* gogo
, Named_object
* named_function
)
6412 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6414 // A list of parameter variables for this function.
6415 std::vector
<Bvariable
*> param_vars
;
6417 // Variables that need to be declared for this function and their
6419 std::vector
<Bvariable
*> vars
;
6420 std::vector
<Expression
*> var_inits
;
6421 std::vector
<Statement
*> var_decls_stmts
;
6422 for (Bindings::const_definitions_iterator p
=
6423 this->block_
->bindings()->begin_definitions();
6424 p
!= this->block_
->bindings()->end_definitions();
6427 Location loc
= (*p
)->location();
6428 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
6430 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6431 Bvariable
* parm_bvar
= bvar
;
6433 // We always pass the receiver to a method as a pointer. If
6434 // the receiver is declared as a non-pointer type, then we
6435 // copy the value into a local variable. For direct interface
6436 // type we pack the pointer into the type.
6437 if ((*p
)->var_value()->is_receiver()
6438 && (*p
)->var_value()->type()->points_to() == NULL
)
6440 std::string name
= (*p
)->name() + ".pointer";
6441 Type
* var_type
= (*p
)->var_value()->type();
6442 Variable
* parm_var
=
6443 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
6445 Named_object
* parm_no
=
6446 Named_object::make_variable(name
, NULL
, parm_var
);
6447 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6449 vars
.push_back(bvar
);
6451 Expression
* parm_ref
=
6452 Expression::make_var_reference(parm_no
, loc
);
6453 Type
* recv_type
= (*p
)->var_value()->type();
6454 if (recv_type
->is_direct_iface_type())
6455 parm_ref
= Expression::pack_direct_iface(recv_type
, parm_ref
, loc
);
6458 Expression::make_dereference(parm_ref
,
6459 Expression::NIL_CHECK_NEEDED
,
6461 if ((*p
)->var_value()->is_in_heap())
6462 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
6463 var_inits
.push_back(parm_ref
);
6465 else if ((*p
)->var_value()->is_in_heap())
6467 // If we take the address of a parameter, then we need
6468 // to copy it into the heap.
6469 std::string parm_name
= (*p
)->name() + ".param";
6470 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
6471 false, true, false, loc
);
6472 Named_object
* parm_no
=
6473 Named_object::make_variable(parm_name
, NULL
, parm_var
);
6474 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6476 vars
.push_back(bvar
);
6477 Expression
* var_ref
=
6478 Expression::make_var_reference(parm_no
, loc
);
6479 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
6480 var_inits
.push_back(var_ref
);
6482 param_vars
.push_back(parm_bvar
);
6484 else if ((*p
)->is_result_variable())
6486 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6488 Type
* type
= (*p
)->result_var_value()->type();
6490 if (!(*p
)->result_var_value()->is_in_heap())
6492 Btype
* btype
= type
->get_backend(gogo
);
6493 Bexpression
* binit
= gogo
->backend()->zero_expression(btype
);
6494 init
= Expression::make_backend(binit
, type
, loc
);
6497 init
= Expression::make_allocation(type
, loc
);
6499 vars
.push_back(bvar
);
6500 var_inits
.push_back(init
);
6502 else if (this->defer_stack_
!= NULL
6503 && (*p
)->is_variable()
6504 && (*p
)->var_value()->is_non_escaping_address_taken()
6505 && !(*p
)->var_value()->is_in_heap())
6507 // Local variable captured by deferred closure needs to be live
6508 // until the end of the function. We create a top-level
6509 // declaration for it.
6510 // TODO: we don't need to do this if the variable is not captured
6511 // by the defer closure. There is no easy way to check it here,
6512 // so we do this for all address-taken variables for now.
6513 Variable
* var
= (*p
)->var_value();
6514 Temporary_statement
* ts
=
6515 Statement::make_temporary(var
->type(), NULL
, var
->location());
6516 ts
->set_is_address_taken();
6517 var
->set_toplevel_decl(ts
);
6518 var_decls_stmts
.push_back(ts
);
6521 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
6523 go_assert(saw_errors());
6527 // If we need a closure variable, make sure to create it.
6528 // It gets installed in the function as a side effect of creation.
6529 if (this->closure_var_
!= NULL
)
6531 go_assert(this->closure_var_
->var_value()->is_closure());
6532 this->closure_var_
->get_backend_variable(gogo
, named_function
);
6535 if (this->block_
!= NULL
)
6537 // Declare variables if necessary.
6538 Bblock
* var_decls
= NULL
;
6539 std::vector
<Bstatement
*> var_decls_bstmt_list
;
6540 Bstatement
* defer_init
= NULL
;
6541 if (!vars
.empty() || this->defer_stack_
!= NULL
)
6544 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
6545 this->block_
->start_location(),
6546 this->block_
->end_location());
6548 if (this->defer_stack_
!= NULL
)
6550 Translate_context
dcontext(gogo
, named_function
, this->block_
,
6552 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
6553 var_decls_bstmt_list
.push_back(defer_init
);
6554 for (std::vector
<Statement
*>::iterator p
= var_decls_stmts
.begin();
6555 p
!= var_decls_stmts
.end();
6558 Bstatement
* bstmt
= (*p
)->get_backend(&dcontext
);
6559 var_decls_bstmt_list
.push_back(bstmt
);
6564 // Build the backend representation for all the statements in the
6566 Translate_context
bcontext(gogo
, named_function
, NULL
, NULL
);
6567 Bblock
* code_block
= this->block_
->get_backend(&bcontext
);
6569 // Initialize variables if necessary.
6570 Translate_context
icontext(gogo
, named_function
, this->block_
,
6572 std::vector
<Bstatement
*> init
;
6573 go_assert(vars
.size() == var_inits
.size());
6574 for (size_t i
= 0; i
< vars
.size(); ++i
)
6576 Bexpression
* binit
= var_inits
[i
]->get_backend(&icontext
);
6577 Bstatement
* init_stmt
=
6578 gogo
->backend()->init_statement(this->fndecl_
, vars
[i
],
6580 init
.push_back(init_stmt
);
6582 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
6584 // Initialize all variables before executing this code block.
6585 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
6586 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
6588 // If we have a defer stack, initialize it at the start of a
6590 Bstatement
* except
= NULL
;
6591 Bstatement
* fini
= NULL
;
6592 if (defer_init
!= NULL
)
6594 // Clean up the defer stack when we leave the function.
6595 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
6597 // Wrap the code for this function in an exception handler to handle
6600 gogo
->backend()->exception_handler_statement(code_stmt
,
6605 // Stick the code into the block we built for the receiver, if
6607 if (var_decls
!= NULL
)
6609 var_decls_bstmt_list
.push_back(code_stmt
);
6610 gogo
->backend()->block_add_statements(var_decls
, var_decls_bstmt_list
);
6611 code_stmt
= gogo
->backend()->block_statement(var_decls
);
6614 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
6616 go_assert(saw_errors());
6621 // If we created a descriptor for the function, make sure we emit it.
6622 if (this->descriptor_
!= NULL
)
6624 Translate_context
dcontext(gogo
, NULL
, NULL
, NULL
);
6625 this->descriptor_
->get_backend(&dcontext
);
6629 // Build the wrappers around function code needed if the function has
6630 // any defer statements. This sets *EXCEPT to an exception handler
6631 // and *FINI to a finally handler.
6634 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
6635 Bstatement
** except
, Bstatement
** fini
)
6637 Location end_loc
= this->block_
->end_location();
6639 // Add an exception handler. This is used if a panic occurs. Its
6640 // purpose is to stop the stack unwinding if a deferred function
6641 // calls recover. There are more details in
6642 // libgo/runtime/go-unwind.c.
6644 std::vector
<Bstatement
*> stmts
;
6645 Expression
* call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6646 this->defer_stack(end_loc
));
6647 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6648 Bexpression
* defer
= call
->get_backend(&context
);
6649 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, defer
));
6651 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6652 if (ret_bstmt
!= NULL
)
6653 stmts
.push_back(ret_bstmt
);
6655 go_assert(*except
== NULL
);
6656 *except
= gogo
->backend()->statement_list(stmts
);
6658 call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6659 this->defer_stack(end_loc
));
6660 defer
= call
->get_backend(&context
);
6662 call
= Runtime::make_call(Runtime::DEFERRETURN
, end_loc
, 1,
6663 this->defer_stack(end_loc
));
6664 Bexpression
* undefer
= call
->get_backend(&context
);
6665 Bstatement
* function_defer
=
6666 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
6668 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
6669 if (this->type_
->results() != NULL
6670 && !this->type_
->results()->empty()
6671 && !this->type_
->results()->front().name().empty())
6673 // If the result variables are named, and we are returning from
6674 // this function rather than panicing through it, we need to
6675 // return them again, because they might have been changed by a
6676 // defer function. The runtime routines set the defer_stack
6677 // variable to true if we are returning from this function.
6679 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6680 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
6682 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
6684 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
6685 Bexpression
* bref
= ref
->get_backend(&context
);
6686 ret
= gogo
->backend()->conditional_expression(this->fndecl_
,
6687 NULL
, bref
, ret
, NULL
,
6689 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, ret
));
6692 go_assert(*fini
== NULL
);
6693 *fini
= gogo
->backend()->statement_list(stmts
);
6696 // Return the statement that assigns values to this function's result struct.
6699 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
6700 Location location
) const
6702 const Typed_identifier_list
* results
= this->type_
->results();
6703 if (results
== NULL
|| results
->empty())
6706 go_assert(this->results_
!= NULL
);
6707 if (this->results_
->size() != results
->size())
6709 go_assert(saw_errors());
6710 return gogo
->backend()->error_statement();
6713 std::vector
<Bexpression
*> vals(results
->size());
6714 for (size_t i
= 0; i
< vals
.size(); ++i
)
6716 Named_object
* no
= (*this->results_
)[i
];
6717 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
6718 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
6719 if (no
->result_var_value()->is_in_heap())
6721 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
6722 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
6726 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
6731 Block::Block(Block
* enclosing
, Location location
)
6732 : enclosing_(enclosing
), statements_(),
6733 bindings_(new Bindings(enclosing
== NULL
6735 : enclosing
->bindings())),
6736 start_location_(location
),
6737 end_location_(Linemap::unknown_location())
6741 // Add a statement to a block.
6744 Block::add_statement(Statement
* statement
)
6746 this->statements_
.push_back(statement
);
6749 // Add a statement to the front of a block. This is slow but is only
6750 // used for reference counts of parameters.
6753 Block::add_statement_at_front(Statement
* statement
)
6755 this->statements_
.insert(this->statements_
.begin(), statement
);
6758 // Replace a statement in a block.
6761 Block::replace_statement(size_t index
, Statement
* s
)
6763 go_assert(index
< this->statements_
.size());
6764 this->statements_
[index
] = s
;
6767 // Add a statement before another statement.
6770 Block::insert_statement_before(size_t index
, Statement
* s
)
6772 go_assert(index
< this->statements_
.size());
6773 this->statements_
.insert(this->statements_
.begin() + index
, s
);
6776 // Add a statement after another statement.
6779 Block::insert_statement_after(size_t index
, Statement
* s
)
6781 go_assert(index
< this->statements_
.size());
6782 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
6785 // Traverse the tree.
6788 Block::traverse(Traverse
* traverse
)
6790 unsigned int traverse_mask
= traverse
->traverse_mask();
6792 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
6794 int t
= traverse
->block(this);
6795 if (t
== TRAVERSE_EXIT
)
6796 return TRAVERSE_EXIT
;
6797 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
6798 return TRAVERSE_CONTINUE
;
6802 & (Traverse::traverse_variables
6803 | Traverse::traverse_constants
6804 | Traverse::traverse_expressions
6805 | Traverse::traverse_types
)) != 0)
6807 const unsigned int e_or_t
= (Traverse::traverse_expressions
6808 | Traverse::traverse_types
);
6809 const unsigned int e_or_t_or_s
= (e_or_t
6810 | Traverse::traverse_statements
);
6811 for (Bindings::const_definitions_iterator pb
=
6812 this->bindings_
->begin_definitions();
6813 pb
!= this->bindings_
->end_definitions();
6816 int t
= TRAVERSE_CONTINUE
;
6817 switch ((*pb
)->classification())
6819 case Named_object::NAMED_OBJECT_CONST
:
6820 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
6821 t
= traverse
->constant(*pb
, false);
6822 if (t
== TRAVERSE_CONTINUE
6823 && (traverse_mask
& e_or_t
) != 0)
6825 Type
* tc
= (*pb
)->const_value()->type();
6827 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
6828 return TRAVERSE_EXIT
;
6829 t
= (*pb
)->const_value()->traverse_expression(traverse
);
6833 case Named_object::NAMED_OBJECT_VAR
:
6834 case Named_object::NAMED_OBJECT_RESULT_VAR
:
6835 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
6836 t
= traverse
->variable(*pb
);
6837 if (t
== TRAVERSE_CONTINUE
6838 && (traverse_mask
& e_or_t
) != 0)
6840 if ((*pb
)->is_result_variable()
6841 || (*pb
)->var_value()->has_type())
6843 Type
* tv
= ((*pb
)->is_variable()
6844 ? (*pb
)->var_value()->type()
6845 : (*pb
)->result_var_value()->type());
6847 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
6848 return TRAVERSE_EXIT
;
6851 if (t
== TRAVERSE_CONTINUE
6852 && (traverse_mask
& e_or_t_or_s
) != 0
6853 && (*pb
)->is_variable())
6854 t
= (*pb
)->var_value()->traverse_expression(traverse
,
6858 case Named_object::NAMED_OBJECT_FUNC
:
6859 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
6862 case Named_object::NAMED_OBJECT_TYPE
:
6863 if ((traverse_mask
& e_or_t
) != 0)
6864 t
= Type::traverse((*pb
)->type_value(), traverse
);
6867 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
6868 case Named_object::NAMED_OBJECT_UNKNOWN
:
6869 case Named_object::NAMED_OBJECT_ERRONEOUS
:
6872 case Named_object::NAMED_OBJECT_PACKAGE
:
6873 case Named_object::NAMED_OBJECT_SINK
:
6880 if (t
== TRAVERSE_EXIT
)
6881 return TRAVERSE_EXIT
;
6885 // No point in checking traverse_mask here--if we got here we always
6886 // want to walk the statements. The traversal can insert new
6887 // statements before or after the current statement. Inserting
6888 // statements before the current statement requires updating I via
6889 // the pointer; those statements will not be traversed. Any new
6890 // statements inserted after the current statement will be traversed
6892 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
6894 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
6895 return TRAVERSE_EXIT
;
6898 return TRAVERSE_CONTINUE
;
6901 // Work out types for unspecified variables and constants.
6904 Block::determine_types()
6906 for (Bindings::const_definitions_iterator pb
=
6907 this->bindings_
->begin_definitions();
6908 pb
!= this->bindings_
->end_definitions();
6911 if ((*pb
)->is_variable())
6912 (*pb
)->var_value()->determine_type();
6913 else if ((*pb
)->is_const())
6914 (*pb
)->const_value()->determine_type();
6917 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
6918 ps
!= this->statements_
.end();
6920 (*ps
)->determine_types();
6923 // Return true if the statements in this block may fall through.
6926 Block::may_fall_through() const
6928 if (this->statements_
.empty())
6930 return this->statements_
.back()->may_fall_through();
6933 // Write export data for a block.
6936 Block::export_block(Export_function_body
* efb
)
6938 for (Block::iterator p
= this->begin();
6944 efb
->increment_indent();
6945 (*p
)->export_statement(efb
);
6946 efb
->decrement_indent();
6948 Location loc
= (*p
)->location();
6949 if ((*p
)->is_block_statement())
6951 // For a block we put the start location on the first brace
6952 // in Block_statement::do_export_statement. Here we put the
6953 // end location on the final brace.
6954 loc
= (*p
)->block_statement()->block()->end_location();
6957 snprintf(buf
, sizeof buf
, " //%d\n", Linemap::location_to_line(loc
));
6958 efb
->write_c_string(buf
);
6962 // Add exported block data to SET, reading from BODY starting at OFF.
6963 // Returns whether the import succeeded.
6966 Block::import_block(Block
* set
, Import_function_body
*ifb
, Location loc
)
6968 Location eloc
= ifb
->location();
6969 Location sloc
= loc
;
6970 const std::string
& body(ifb
->body());
6971 size_t off
= ifb
->off();
6972 while (off
< body
.length())
6974 int indent
= ifb
->indent();
6975 if (off
+ indent
>= body
.length())
6978 "invalid export data for %qs: insufficient indentation",
6979 ifb
->name().c_str());
6982 for (int i
= 0; i
< indent
- 1; i
++)
6984 if (body
[off
+ i
] != ' ')
6987 "invalid export data for %qs: bad indentation",
6988 ifb
->name().c_str());
6993 bool at_end
= false;
6994 if (body
[off
+ indent
- 1] == '}')
6996 else if (body
[off
+ indent
- 1] != ' ')
6999 "invalid export data for %qs: bad indentation",
7000 ifb
->name().c_str());
7006 size_t nl
= body
.find('\n', off
);
7007 if (nl
== std::string::npos
)
7009 go_error_at(eloc
, "invalid export data for %qs: missing newline",
7010 ifb
->name().c_str());
7014 size_t lineno_pos
= body
.find(" //", off
);
7015 if (lineno_pos
== std::string::npos
|| lineno_pos
>= nl
)
7017 go_error_at(eloc
, "invalid export data for %qs: missing line number",
7018 ifb
->name().c_str());
7022 unsigned int lineno
= 0;
7023 for (size_t i
= lineno_pos
+ 3; i
< nl
; ++i
)
7026 if (c
< '0' || c
> '9')
7029 "invalid export data for %qs: invalid line number",
7030 ifb
->name().c_str());
7033 lineno
= lineno
* 10 + c
- '0';
7036 ifb
->gogo()->linemap()->start_line(lineno
, 1);
7037 sloc
= ifb
->gogo()->linemap()->get_location(0);
7041 // An if statement can have an "else" following the "}", in
7042 // which case we want to leave the offset where it is, just
7043 // after the "}". We don't get the block ending location
7044 // quite right for if statements.
7045 if (body
.compare(off
, 6, " else ") != 0)
7051 Statement
* s
= Statement::import_statement(ifb
, sloc
);
7055 set
->add_statement(s
);
7057 size_t at
= ifb
->off();
7065 set
->set_end_location(sloc
);
7069 // Convert a block to the backend representation.
7072 Block::get_backend(Translate_context
* context
)
7074 Gogo
* gogo
= context
->gogo();
7075 Named_object
* function
= context
->function();
7076 std::vector
<Bvariable
*> vars
;
7077 vars
.reserve(this->bindings_
->size_definitions());
7078 for (Bindings::const_definitions_iterator pv
=
7079 this->bindings_
->begin_definitions();
7080 pv
!= this->bindings_
->end_definitions();
7083 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
7084 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
7087 go_assert(function
!= NULL
);
7088 Bfunction
* bfunction
=
7089 function
->func_value()->get_or_make_decl(gogo
, function
);
7090 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
7091 vars
, this->start_location_
,
7092 this->end_location_
);
7094 Translate_context
subcontext(gogo
, function
, this, ret
);
7095 std::vector
<Bstatement
*> bstatements
;
7096 bstatements
.reserve(this->statements_
.size());
7097 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
7098 p
!= this->statements_
.end();
7100 bstatements
.push_back((*p
)->get_backend(&subcontext
));
7102 context
->backend()->block_add_statements(ret
, bstatements
);
7107 // Class Bindings_snapshot.
7109 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
7110 : block_(b
), counts_(), location_(location
)
7114 this->counts_
.push_back(b
->bindings()->size_definitions());
7119 // Report errors appropriate for a goto from B to this.
7122 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
7125 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
7127 this->check_goto_defs(loc
, this->block_
,
7128 this->block_
->bindings()->size_definitions(),
7132 // Report errors appropriate for a goto from this to B.
7135 Bindings_snapshot::check_goto_to(const Block
* b
)
7138 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
7140 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
7141 b
->bindings()->size_definitions());
7144 // Report errors appropriate for a goto at LOC from BFROM to BTO.
7145 // Return true if all is well, false if we reported an error. If this
7146 // returns true, it sets *PINDEX to the number of blocks BTO is above
7150 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
7151 const Block
* bto
, size_t* pindex
)
7153 // It is an error if BTO is not either BFROM or above BFROM.
7155 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
7159 go_error_at(loc
, "goto jumps into block");
7160 go_inform(bto
->start_location(), "goto target block starts here");
7168 // Report errors appropriate for a goto at LOC ending at BLOCK, where
7169 // CFROM is the number of names defined at the point of the goto and
7170 // CTO is the number of names defined at the point of the label.
7173 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
7174 size_t cfrom
, size_t cto
)
7178 Bindings::const_definitions_iterator p
=
7179 block
->bindings()->begin_definitions();
7180 for (size_t i
= 0; i
< cfrom
; ++i
)
7182 go_assert(p
!= block
->bindings()->end_definitions());
7185 go_assert(p
!= block
->bindings()->end_definitions());
7187 for (; p
!= block
->bindings()->end_definitions(); ++p
)
7189 if ((*p
)->is_variable())
7191 std::string n
= (*p
)->message_name();
7192 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
7193 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
7199 // Class Function_declaration.
7201 // Whether this declares a method.
7204 Function_declaration::is_method() const
7206 return this->fntype_
->is_method();
7209 // Whether this method should not be included in the type descriptor.
7212 Function_declaration::nointerface() const
7214 go_assert(this->is_method());
7215 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
7218 // Record that this method should not be included in the type
7222 Function_declaration::set_nointerface()
7224 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
7227 // Import an inlinable function. This is used for an inlinable
7228 // function whose body is recorded in the export data. Parse the
7229 // export data into a Block and create a regular function using that
7230 // Block as its body. Redeclare this function declaration as the
7234 Function_declaration::import_function_body(Gogo
* gogo
, Named_object
* no
)
7236 go_assert(no
->func_declaration_value() == this);
7237 go_assert(no
->package() != NULL
);
7238 const std::string
& body(this->imported_body_
);
7239 go_assert(!body
.empty());
7241 // Read the "//FILE:LINE" comment starts the export data.
7244 if (this->is_method())
7247 for (; i
< indent
; i
++)
7249 if (body
.at(i
) != ' ')
7251 go_error_at(this->location_
,
7252 "invalid export body for %qs: bad initial indentation",
7253 no
->message_name().c_str());
7258 if (body
.substr(i
, 2) != "//")
7260 go_error_at(this->location_
,
7261 "invalid export body for %qs: missing file comment",
7262 no
->message_name().c_str());
7266 size_t colon
= body
.find(':', i
+ 2);
7267 size_t nl
= body
.find('\n', i
+ 2);
7268 if (nl
== std::string::npos
)
7270 go_error_at(this->location_
,
7271 "invalid export body for %qs: missing file name",
7272 no
->message_name().c_str());
7275 if (colon
== std::string::npos
|| nl
< colon
)
7277 go_error_at(this->location_
,
7278 "invalid export body for %qs: missing initial line number",
7279 no
->message_name().c_str());
7283 std::string file
= body
.substr(i
+ 2, colon
- (i
+ 2));
7284 std::string linestr
= body
.substr(colon
+ 1, nl
- (colon
+ 1));
7286 long linenol
= strtol(linestr
.c_str(), &end
, 10);
7289 go_error_at(this->location_
,
7290 "invalid export body for %qs: invalid initial line number",
7291 no
->message_name().c_str());
7294 unsigned int lineno
= static_cast<unsigned int>(linenol
);
7296 // Turn the file/line into a location.
7298 char* alc
= new char[file
.length() + 1];
7299 memcpy(alc
, file
.data(), file
.length());
7300 alc
[file
.length()] = '\0';
7301 gogo
->linemap()->start_file(alc
, lineno
);
7302 gogo
->linemap()->start_line(lineno
, 1);
7303 Location start_loc
= gogo
->linemap()->get_location(0);
7305 // Define the function with an outer block that declares the
7308 Function_type
* fntype
= this->fntype_
;
7310 Block
* outer
= new Block(NULL
, start_loc
);
7312 Function
* fn
= new Function(fntype
, NULL
, outer
, start_loc
);
7313 fn
->set_is_inline_only();
7315 if (fntype
->is_method())
7317 if (this->nointerface())
7318 fn
->set_nointerface();
7319 const Typed_identifier
* receiver
= fntype
->receiver();
7320 Variable
* recv_param
= new Variable(receiver
->type(), NULL
, false,
7321 true, true, start_loc
);
7323 std::string rname
= receiver
->name();
7324 unsigned rcounter
= 0;
7326 // We need to give a nameless receiver a name to avoid having it
7327 // clash with some other nameless param. FIXME.
7328 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
7330 outer
->bindings()->add_variable(rname
, NULL
, recv_param
);
7333 const Typed_identifier_list
* params
= fntype
->parameters();
7334 bool is_varargs
= fntype
->is_varargs();
7335 unsigned pcounter
= 0;
7338 for (Typed_identifier_list::const_iterator p
= params
->begin();
7342 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
7344 if (is_varargs
&& p
+ 1 == params
->end())
7345 param
->set_is_varargs_parameter();
7347 std::string pname
= p
->name();
7349 // We need to give each nameless parameter a non-empty name to avoid
7350 // having it clash with some other nameless param. FIXME.
7351 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
7353 outer
->bindings()->add_variable(pname
, NULL
, param
);
7357 fn
->create_result_variables(gogo
);
7359 if (!fntype
->is_method())
7361 const Package
* package
= no
->package();
7362 no
= package
->bindings()->add_function(no
->name(), package
, fn
);
7366 Named_type
* rtype
= fntype
->receiver()->type()->deref()->named_type();
7367 go_assert(rtype
!= NULL
);
7368 no
= rtype
->add_method(no
->name(), fn
);
7369 const Package
* package
= rtype
->named_object()->package();
7370 package
->bindings()->add_method(no
);
7373 Import_function_body
ifb(gogo
, this->imp_
, no
, body
, nl
+ 1, outer
, indent
);
7375 if (!Block::import_block(outer
, &ifb
, start_loc
))
7378 gogo
->lower_block(no
, outer
);
7379 outer
->determine_types();
7381 gogo
->add_imported_inline_function(no
);
7384 // Return the function descriptor.
7387 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
7389 go_assert(!this->fntype_
->is_method());
7390 if (this->descriptor_
== NULL
)
7391 this->descriptor_
= Expression::make_func_descriptor(no
);
7392 return this->descriptor_
;
7397 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
7398 bool is_parameter
, bool is_receiver
,
7400 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
7401 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
7402 is_closure_(false), is_receiver_(is_receiver
),
7403 is_varargs_parameter_(false), is_used_(false),
7404 is_address_taken_(false), is_non_escaping_address_taken_(false),
7405 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
7406 type_from_init_tuple_(false), type_from_range_index_(false),
7407 type_from_range_value_(false), type_from_chan_element_(false),
7408 is_type_switch_var_(false), determined_type_(false),
7409 in_unique_section_(false), is_referenced_by_inline_(false),
7410 toplevel_decl_(NULL
)
7412 go_assert(type
!= NULL
|| init
!= NULL
);
7413 go_assert(!is_parameter
|| init
== NULL
);
7416 // Traverse the initializer expression.
7419 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
7421 if (this->preinit_
!= NULL
)
7423 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
7424 return TRAVERSE_EXIT
;
7426 if (this->init_
!= NULL
7428 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
7431 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
7432 return TRAVERSE_EXIT
;
7434 return TRAVERSE_CONTINUE
;
7437 // Lower the initialization expression after parsing is complete.
7440 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
7441 Statement_inserter
* inserter
)
7443 Named_object
* dep
= gogo
->var_depends_on(this);
7444 if (dep
!= NULL
&& dep
->is_variable())
7445 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
7447 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
7451 // We will give an error elsewhere, this is just to prevent
7452 // an infinite loop.
7457 Statement_inserter global_inserter
;
7458 if (this->is_global_
)
7460 global_inserter
= Statement_inserter(gogo
, this);
7461 inserter
= &global_inserter
;
7464 gogo
->lower_expression(function
, inserter
, &this->init_
);
7466 this->seen_
= false;
7468 this->init_is_lowered_
= true;
7472 // Flatten the initialization expression after ordering evaluations.
7475 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
7476 Statement_inserter
* inserter
)
7478 Named_object
* dep
= gogo
->var_depends_on(this);
7479 if (dep
!= NULL
&& dep
->is_variable())
7480 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
7482 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
7486 // We will give an error elsewhere, this is just to prevent
7487 // an infinite loop.
7492 Statement_inserter global_inserter
;
7493 if (this->is_global_
)
7495 global_inserter
= Statement_inserter(gogo
, this);
7496 inserter
= &global_inserter
;
7499 gogo
->flatten_expression(function
, inserter
, &this->init_
);
7501 // If an interface conversion is needed, we need a temporary
7503 if (this->type_
!= NULL
7504 && !Type::are_identical(this->type_
, this->init_
->type(),
7505 Type::COMPARE_ERRORS
| Type::COMPARE_TAGS
,
7507 && this->init_
->type()->interface_type() != NULL
7508 && !this->init_
->is_variable())
7510 Temporary_statement
* temp
=
7511 Statement::make_temporary(NULL
, this->init_
, this->location_
);
7512 inserter
->insert(temp
);
7513 this->init_
= Expression::make_temporary_reference(temp
,
7517 this->seen_
= false;
7518 this->init_is_flattened_
= true;
7522 // Get the preinit block.
7525 Variable::preinit_block(Gogo
* gogo
)
7527 go_assert(this->is_global_
);
7528 if (this->preinit_
== NULL
)
7529 this->preinit_
= new Block(NULL
, this->location());
7531 // If a global variable has a preinitialization statement, then we
7532 // need to have an initialization function.
7533 gogo
->set_need_init_fn();
7535 return this->preinit_
;
7538 // Add a statement to be run before the initialization expression.
7541 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
7543 Block
* b
= this->preinit_block(gogo
);
7544 b
->add_statement(s
);
7545 b
->set_end_location(s
->location());
7548 // Whether this variable has a type.
7551 Variable::has_type() const
7553 if (this->type_
== NULL
)
7556 // A variable created in a type switch case nil does not actually
7557 // have a type yet. It will be changed to use the initializer's
7558 // type in determine_type.
7559 if (this->is_type_switch_var_
7560 && this->type_
->is_nil_constant_as_type())
7566 // In an assignment which sets a variable to a tuple of EXPR, return
7567 // the type of the first element of the tuple.
7570 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
7572 if (expr
->map_index_expression() != NULL
)
7574 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
7576 return Type::make_error_type();
7577 return mt
->val_type();
7579 else if (expr
->receive_expression() != NULL
)
7581 Expression
* channel
= expr
->receive_expression()->channel();
7582 Type
* channel_type
= channel
->type();
7583 if (channel_type
->channel_type() == NULL
)
7584 return Type::make_error_type();
7585 return channel_type
->channel_type()->element_type();
7590 go_error_at(this->location(), "invalid tuple definition");
7591 return Type::make_error_type();
7595 // Given EXPR used in a range clause, return either the index type or
7596 // the value type of the range, depending upon GET_INDEX_TYPE.
7599 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
7600 bool report_error
) const
7602 Type
* t
= expr
->type();
7603 if (t
->array_type() != NULL
7604 || (t
->points_to() != NULL
7605 && t
->points_to()->array_type() != NULL
7606 && !t
->points_to()->is_slice_type()))
7609 return Type::lookup_integer_type("int");
7611 return t
->deref()->array_type()->element_type();
7613 else if (t
->is_string_type())
7616 return Type::lookup_integer_type("int");
7618 return Type::lookup_integer_type("int32");
7620 else if (t
->map_type() != NULL
)
7623 return t
->map_type()->key_type();
7625 return t
->map_type()->val_type();
7627 else if (t
->channel_type() != NULL
)
7630 return t
->channel_type()->element_type();
7634 go_error_at(this->location(),
7635 ("invalid definition of value variable "
7636 "for channel range"));
7637 return Type::make_error_type();
7643 go_error_at(this->location(), "invalid type for range clause");
7644 return Type::make_error_type();
7648 // EXPR should be a channel. Return the channel's element type.
7651 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
7653 Type
* t
= expr
->type();
7654 if (t
->channel_type() != NULL
)
7655 return t
->channel_type()->element_type();
7659 go_error_at(this->location(), "expected channel");
7660 return Type::make_error_type();
7664 // Return the type of the Variable. This may be called before
7665 // Variable::determine_type is called, which means that we may need to
7666 // get the type from the initializer. FIXME: If we combine lowering
7667 // with type determination, then this should be unnecessary.
7672 // A variable in a type switch with a nil case will have the wrong
7673 // type here. This gets fixed up in determine_type, below.
7674 Type
* type
= this->type_
;
7675 Expression
* init
= this->init_
;
7676 if (this->is_type_switch_var_
7678 && this->type_
->is_nil_constant_as_type())
7680 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7681 go_assert(tge
!= NULL
);
7688 if (this->type_
== NULL
|| !this->type_
->is_error_type())
7690 go_error_at(this->location_
, "variable initializer refers to itself");
7691 this->type_
= Type::make_error_type();
7700 else if (this->type_from_init_tuple_
)
7701 type
= this->type_from_tuple(init
, false);
7702 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7703 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
7704 else if (this->type_from_chan_element_
)
7705 type
= this->type_from_chan_element(init
, false);
7708 go_assert(init
!= NULL
);
7709 type
= init
->type();
7710 go_assert(type
!= NULL
);
7712 // Variables should not have abstract types.
7713 if (type
->is_abstract())
7714 type
= type
->make_non_abstract_type();
7716 if (type
->is_void_type())
7717 type
= Type::make_error_type();
7720 this->seen_
= false;
7725 // Fetch the type from a const pointer, in which case it should have
7726 // been set already.
7729 Variable::type() const
7731 go_assert(this->type_
!= NULL
);
7735 // Set the type if necessary.
7738 Variable::determine_type()
7740 if (this->determined_type_
)
7742 this->determined_type_
= true;
7744 if (this->preinit_
!= NULL
)
7745 this->preinit_
->determine_types();
7747 // A variable in a type switch with a nil case will have the wrong
7748 // type here. It will have an initializer which is a type guard.
7749 // We want to initialize it to the value without the type guard, and
7750 // use the type of that value as well.
7751 if (this->is_type_switch_var_
7752 && this->type_
!= NULL
7753 && this->type_
->is_nil_constant_as_type())
7755 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7756 go_assert(tge
!= NULL
);
7758 this->init_
= tge
->expr();
7761 if (this->init_
== NULL
)
7762 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
7763 else if (this->type_from_init_tuple_
)
7765 Expression
*init
= this->init_
;
7766 init
->determine_type_no_context();
7767 this->type_
= this->type_from_tuple(init
, true);
7770 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7772 Expression
* init
= this->init_
;
7773 init
->determine_type_no_context();
7774 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
7778 else if (this->type_from_chan_element_
)
7780 Expression
* init
= this->init_
;
7781 init
->determine_type_no_context();
7782 this->type_
= this->type_from_chan_element(init
, true);
7787 Type_context
context(this->type_
, false);
7788 this->init_
->determine_type(&context
);
7789 if (this->type_
== NULL
)
7791 Type
* type
= this->init_
->type();
7792 go_assert(type
!= NULL
);
7793 if (type
->is_abstract())
7794 type
= type
->make_non_abstract_type();
7796 if (type
->is_void_type())
7798 go_error_at(this->location_
, "variable has no type");
7799 type
= Type::make_error_type();
7801 else if (type
->is_nil_type())
7803 go_error_at(this->location_
, "variable defined to nil type");
7804 type
= Type::make_error_type();
7806 else if (type
->is_call_multiple_result_type())
7808 go_error_at(this->location_
,
7809 "single variable set to multiple-value function call");
7810 type
= Type::make_error_type();
7818 // Get the initial value of a variable. This does not
7819 // consider whether the variable is in the heap--it returns the
7820 // initial value as though it were always stored in the stack.
7823 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
7825 go_assert(this->preinit_
== NULL
);
7826 Location loc
= this->location();
7827 if (this->init_
== NULL
)
7829 go_assert(!this->is_parameter_
);
7830 if (this->is_global_
|| this->is_in_heap())
7832 Btype
* btype
= this->type()->get_backend(gogo
);
7833 return gogo
->backend()->zero_expression(btype
);
7837 Translate_context
context(gogo
, function
, NULL
, NULL
);
7838 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
7839 return init
->get_backend(&context
);
7843 // Get the initial value of a variable when a block is required.
7844 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7847 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
7848 Bvariable
* var_decl
)
7850 go_assert(this->preinit_
!= NULL
);
7852 // We want to add the variable assignment to the end of the preinit
7855 Translate_context
context(gogo
, function
, NULL
, NULL
);
7856 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
7857 Bfunction
* bfunction
=
7858 function
->func_value()->get_or_make_decl(gogo
, function
);
7860 // It's possible to have pre-init statements without an initializer
7861 // if the pre-init statements set the variable.
7862 Bstatement
* decl_init
= NULL
;
7863 if (this->init_
!= NULL
)
7865 if (var_decl
== NULL
)
7867 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
7868 decl_init
= gogo
->backend()->expression_statement(bfunction
,
7873 Location loc
= this->location();
7874 Expression
* val_expr
=
7875 Expression::make_cast(this->type(), this->init_
, loc
);
7876 Bexpression
* val
= val_expr
->get_backend(&context
);
7877 Bexpression
* var_ref
=
7878 gogo
->backend()->var_expression(var_decl
, loc
);
7879 decl_init
= gogo
->backend()->assignment_statement(bfunction
, var_ref
,
7883 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
7884 if (decl_init
!= NULL
)
7885 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
7889 // Export the variable
7892 Variable::export_var(Export
* exp
, const Named_object
* no
) const
7894 go_assert(this->is_global_
);
7895 exp
->write_c_string("var ");
7896 if (no
->package() != NULL
)
7899 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
7900 exp
->write_c_string(buf
);
7903 if (!Gogo::is_hidden_name(no
->name()))
7904 exp
->write_string(no
->name());
7907 exp
->write_c_string(".");
7908 exp
->write_string(Gogo::unpack_hidden_name(no
->name()));
7911 exp
->write_c_string(" ");
7912 exp
->write_type(this->type());
7913 exp
->write_c_string("\n");
7916 // Import a variable.
7919 Variable::import_var(Import
* imp
, std::string
* pname
, Package
** ppkg
,
7920 bool* pis_exported
, Type
** ptype
)
7922 imp
->require_c_string("var ");
7923 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
7925 go_error_at(imp
->location(),
7926 "import error at %d: bad variable name in export data",
7930 imp
->require_c_string(" ");
7931 *ptype
= imp
->read_type();
7932 imp
->require_semicolon_if_old_version();
7933 imp
->require_c_string("\n");
7937 // Convert a variable to the backend representation.
7940 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
7941 const Package
* package
, const std::string
& name
)
7943 if (this->backend_
== NULL
)
7945 Backend
* backend
= gogo
->backend();
7946 Type
* type
= this->type_
;
7947 if (type
->is_error_type()
7948 || (type
->is_undefined()
7949 && (!this->is_global_
|| package
== NULL
)))
7950 this->backend_
= backend
->error_variable();
7953 bool is_parameter
= this->is_parameter_
;
7954 if (this->is_receiver_
&& type
->points_to() == NULL
)
7955 is_parameter
= false;
7956 if (this->is_in_heap())
7958 is_parameter
= false;
7959 type
= Type::make_pointer_type(type
);
7962 const std::string n
= Gogo::unpack_hidden_name(name
);
7963 Btype
* btype
= type
->get_backend(gogo
);
7966 if (Map_type::is_zero_value(this))
7967 bvar
= Map_type::backend_zero_value(gogo
);
7968 else if (this->is_global_
)
7970 std::string
var_name(package
!= NULL
7971 ? package
->package_name()
7972 : gogo
->package_name());
7973 var_name
.push_back('.');
7976 std::string
asm_name(gogo
->global_var_asm_name(name
, package
));
7978 bool is_hidden
= Gogo::is_hidden_name(name
);
7979 // Hack to export runtime.writeBarrier. FIXME.
7980 // This is because go:linkname doesn't work on variables.
7981 if (gogo
->compiling_runtime()
7982 && var_name
== "runtime.writeBarrier")
7985 // If an inline body refers to this variable, then it
7986 // needs to be visible in the symbol table.
7987 if (this->is_referenced_by_inline_
)
7990 // If this variable is in a different package, then it
7991 // can't be treated as a hidden symbol. This case can
7992 // arise when an inlined function refers to a
7993 // package-scope unexported variable.
7994 if (package
!= NULL
)
7997 bvar
= backend
->global_variable(var_name
,
8002 this->in_unique_section_
,
8005 else if (function
== NULL
)
8007 go_assert(saw_errors());
8008 bvar
= backend
->error_variable();
8012 Bfunction
* bfunction
= function
->func_value()->get_decl();
8013 bool is_address_taken
= (this->is_non_escaping_address_taken_
8014 && !this->is_in_heap());
8015 if (this->is_closure())
8016 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
8018 else if (is_parameter
)
8019 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
8024 Bvariable
* bvar_decl
= NULL
;
8025 if (this->toplevel_decl_
!= NULL
)
8027 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
8028 bvar_decl
= this->toplevel_decl_
->temporary_statement()
8029 ->get_backend_variable(&context
);
8031 bvar
= backend
->local_variable(bfunction
, n
, btype
,
8037 this->backend_
= bvar
;
8040 return this->backend_
;
8043 // Class Result_variable.
8045 // Convert a result variable to the backend representation.
8048 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
8049 const std::string
& name
)
8051 if (this->backend_
== NULL
)
8053 Backend
* backend
= gogo
->backend();
8054 Type
* type
= this->type_
;
8055 if (type
->is_error())
8056 this->backend_
= backend
->error_variable();
8059 if (this->is_in_heap())
8060 type
= Type::make_pointer_type(type
);
8061 Btype
* btype
= type
->get_backend(gogo
);
8062 Bfunction
* bfunction
= function
->func_value()->get_decl();
8063 std::string n
= Gogo::unpack_hidden_name(name
);
8064 bool is_address_taken
= (this->is_non_escaping_address_taken_
8065 && !this->is_in_heap());
8066 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
8067 NULL
, is_address_taken
,
8071 return this->backend_
;
8074 // Class Named_constant.
8076 // Set the type of a named constant. This is only used to set the
8077 // type to an error type.
8080 Named_constant::set_type(Type
* t
)
8082 go_assert(this->type_
== NULL
|| t
->is_error_type());
8086 // Traverse the initializer expression.
8089 Named_constant::traverse_expression(Traverse
* traverse
)
8091 return Expression::traverse(&this->expr_
, traverse
);
8094 // Determine the type of the constant.
8097 Named_constant::determine_type()
8099 if (this->type_
!= NULL
)
8101 Type_context
context(this->type_
, false);
8102 this->expr_
->determine_type(&context
);
8106 // A constant may have an abstract type.
8107 Type_context
context(NULL
, true);
8108 this->expr_
->determine_type(&context
);
8109 this->type_
= this->expr_
->type();
8110 go_assert(this->type_
!= NULL
);
8114 // Indicate that we found and reported an error for this constant.
8117 Named_constant::set_error()
8119 this->type_
= Type::make_error_type();
8120 this->expr_
= Expression::make_error(this->location_
);
8123 // Export a constant.
8126 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
8128 exp
->write_c_string("const ");
8129 exp
->write_string(name
);
8130 exp
->write_c_string(" ");
8131 if (!this->type_
->is_abstract())
8133 exp
->write_type(this->type_
);
8134 exp
->write_c_string(" ");
8136 exp
->write_c_string("= ");
8138 Export_function_body
efb(exp
, 0);
8139 if (!this->type_
->is_abstract())
8140 efb
.set_type_context(this->type_
);
8141 this->expr()->export_expression(&efb
);
8142 exp
->write_string(efb
.body());
8144 exp
->write_c_string("\n");
8147 // Import a constant.
8150 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
8153 imp
->require_c_string("const ");
8154 *pname
= imp
->read_identifier();
8155 imp
->require_c_string(" ");
8156 if (imp
->peek_char() == '=')
8160 *ptype
= imp
->read_type();
8161 imp
->require_c_string(" ");
8163 imp
->require_c_string("= ");
8164 *pexpr
= Expression::import_expression(imp
, imp
->location());
8165 imp
->require_semicolon_if_old_version();
8166 imp
->require_c_string("\n");
8169 // Get the backend representation.
8172 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
8174 if (this->bconst_
== NULL
)
8176 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
8177 Type
* type
= this->type();
8178 Location loc
= this->location();
8180 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
8181 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
8182 if (type
!= NULL
&& type
->is_numeric_type())
8184 Btype
* btype
= type
->get_backend(gogo
);
8185 std::string name
= const_no
->get_id(gogo
);
8187 gogo
->backend()->named_constant_expression(btype
, name
,
8190 this->bconst_
= const_decl
;
8192 return this->bconst_
;
8198 Type_declaration::add_method(const std::string
& name
, Function
* function
)
8200 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
8201 this->methods_
.push_back(ret
);
8205 // Add a method declaration.
8208 Type_declaration::add_method_declaration(const std::string
& name
,
8210 Function_type
* type
,
8213 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
8215 this->methods_
.push_back(ret
);
8219 // Return whether any methods are defined.
8222 Type_declaration::has_methods() const
8224 return !this->methods_
.empty();
8227 // Define methods for the real type.
8230 Type_declaration::define_methods(Named_type
* nt
)
8232 if (this->methods_
.empty())
8235 while (nt
->is_alias())
8237 Type
*t
= nt
->real_type()->forwarded();
8238 if (t
->named_type() != NULL
)
8239 nt
= t
->named_type();
8240 else if (t
->forward_declaration_type() != NULL
)
8242 Named_object
* no
= t
->forward_declaration_type()->named_object();
8243 Type_declaration
* td
= no
->type_declaration_value();
8244 td
->methods_
.insert(td
->methods_
.end(), this->methods_
.begin(),
8245 this->methods_
.end());
8246 this->methods_
.clear();
8251 for (std::vector
<Named_object
*>::const_iterator p
=
8252 this->methods_
.begin();
8253 p
!= this->methods_
.end();
8255 go_error_at((*p
)->location(),
8256 ("invalid receiver type "
8257 "(receiver must be a named type)"));
8262 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
8263 p
!= this->methods_
.end();
8266 if ((*p
)->is_function_declaration()
8267 || !(*p
)->func_value()->is_sink())
8268 nt
->add_existing_method(*p
);
8272 // We are using the type. Return true if we should issue a warning.
8275 Type_declaration::using_type()
8277 bool ret
= !this->issued_warning_
;
8278 this->issued_warning_
= true;
8282 // Class Unknown_name.
8284 // Set the real named object.
8287 Unknown_name::set_real_named_object(Named_object
* no
)
8289 go_assert(this->real_named_object_
== NULL
);
8290 go_assert(!no
->is_unknown());
8291 this->real_named_object_
= no
;
8294 // Class Named_object.
8296 Named_object::Named_object(const std::string
& name
,
8297 const Package
* package
,
8298 Classification classification
)
8299 : name_(name
), package_(package
), classification_(classification
),
8300 is_redefinition_(false)
8302 if (Gogo::is_sink_name(name
))
8303 go_assert(classification
== NAMED_OBJECT_SINK
);
8306 // Make an unknown name. This is used by the parser. The name must
8307 // be resolved later. Unknown names are only added in the current
8311 Named_object::make_unknown_name(const std::string
& name
,
8314 Named_object
* named_object
= new Named_object(name
, NULL
,
8315 NAMED_OBJECT_UNKNOWN
);
8316 Unknown_name
* value
= new Unknown_name(location
);
8317 named_object
->u_
.unknown_value
= value
;
8318 return named_object
;
8324 Named_object::make_constant(const Typed_identifier
& tid
,
8325 const Package
* package
, Expression
* expr
,
8328 Named_object
* named_object
= new Named_object(tid
.name(), package
,
8329 NAMED_OBJECT_CONST
);
8330 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
8333 named_object
->u_
.const_value
= named_constant
;
8334 return named_object
;
8337 // Make a named type.
8340 Named_object::make_type(const std::string
& name
, const Package
* package
,
8341 Type
* type
, Location location
)
8343 Named_object
* named_object
= new Named_object(name
, package
,
8345 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
8346 named_object
->u_
.type_value
= named_type
;
8347 return named_object
;
8350 // Make a type declaration.
8353 Named_object::make_type_declaration(const std::string
& name
,
8354 const Package
* package
,
8357 Named_object
* named_object
= new Named_object(name
, package
,
8358 NAMED_OBJECT_TYPE_DECLARATION
);
8359 Type_declaration
* type_declaration
= new Type_declaration(location
);
8360 named_object
->u_
.type_declaration
= type_declaration
;
8361 return named_object
;
8367 Named_object::make_variable(const std::string
& name
, const Package
* package
,
8370 Named_object
* named_object
= new Named_object(name
, package
,
8372 named_object
->u_
.var_value
= variable
;
8373 return named_object
;
8376 // Make a result variable.
8379 Named_object::make_result_variable(const std::string
& name
,
8380 Result_variable
* result
)
8382 Named_object
* named_object
= new Named_object(name
, NULL
,
8383 NAMED_OBJECT_RESULT_VAR
);
8384 named_object
->u_
.result_var_value
= result
;
8385 return named_object
;
8388 // Make a sink. This is used for the special blank identifier _.
8391 Named_object::make_sink()
8393 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
8396 // Make a named function.
8399 Named_object::make_function(const std::string
& name
, const Package
* package
,
8402 Named_object
* named_object
= new Named_object(name
, package
,
8404 named_object
->u_
.func_value
= function
;
8405 return named_object
;
8408 // Make a function declaration.
8411 Named_object::make_function_declaration(const std::string
& name
,
8412 const Package
* package
,
8413 Function_type
* fntype
,
8416 Named_object
* named_object
= new Named_object(name
, package
,
8417 NAMED_OBJECT_FUNC_DECLARATION
);
8418 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
8419 named_object
->u_
.func_declaration_value
= func_decl
;
8420 return named_object
;
8426 Named_object::make_package(const std::string
& alias
, Package
* package
)
8428 Named_object
* named_object
= new Named_object(alias
, NULL
,
8429 NAMED_OBJECT_PACKAGE
);
8430 named_object
->u_
.package_value
= package
;
8431 return named_object
;
8434 // Return the name to use in an error message.
8437 Named_object::message_name() const
8439 if (this->package_
== NULL
)
8440 return Gogo::message_name(this->name_
);
8442 if (this->package_
->has_package_name())
8443 ret
= this->package_
->package_name();
8445 ret
= this->package_
->pkgpath();
8446 ret
= Gogo::message_name(ret
);
8448 ret
+= Gogo::message_name(this->name_
);
8452 // Set the type when a declaration is defined.
8455 Named_object::set_type_value(Named_type
* named_type
)
8457 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
8458 Type_declaration
* td
= this->u_
.type_declaration
;
8459 td
->define_methods(named_type
);
8461 Named_object
* in_function
= td
->in_function(&index
);
8462 if (in_function
!= NULL
)
8463 named_type
->set_in_function(in_function
, index
);
8465 this->classification_
= NAMED_OBJECT_TYPE
;
8466 this->u_
.type_value
= named_type
;
8469 // Define a function which was previously declared.
8472 Named_object::set_function_value(Function
* function
)
8474 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
8475 if (this->func_declaration_value()->has_descriptor())
8477 Expression
* descriptor
=
8478 this->func_declaration_value()->descriptor(NULL
, NULL
);
8479 function
->set_descriptor(descriptor
);
8481 this->classification_
= NAMED_OBJECT_FUNC
;
8482 // FIXME: We should free the old value.
8483 this->u_
.func_value
= function
;
8486 // Declare an unknown object as a type declaration.
8489 Named_object::declare_as_type()
8491 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
8492 Unknown_name
* unk
= this->u_
.unknown_value
;
8493 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
8494 this->u_
.type_declaration
= new Type_declaration(unk
->location());
8498 // Return the location of a named object.
8501 Named_object::location() const
8503 switch (this->classification_
)
8506 case NAMED_OBJECT_UNINITIALIZED
:
8509 case NAMED_OBJECT_ERRONEOUS
:
8510 return Linemap::unknown_location();
8512 case NAMED_OBJECT_UNKNOWN
:
8513 return this->unknown_value()->location();
8515 case NAMED_OBJECT_CONST
:
8516 return this->const_value()->location();
8518 case NAMED_OBJECT_TYPE
:
8519 return this->type_value()->location();
8521 case NAMED_OBJECT_TYPE_DECLARATION
:
8522 return this->type_declaration_value()->location();
8524 case NAMED_OBJECT_VAR
:
8525 return this->var_value()->location();
8527 case NAMED_OBJECT_RESULT_VAR
:
8528 return this->result_var_value()->location();
8530 case NAMED_OBJECT_SINK
:
8533 case NAMED_OBJECT_FUNC
:
8534 return this->func_value()->location();
8536 case NAMED_OBJECT_FUNC_DECLARATION
:
8537 return this->func_declaration_value()->location();
8539 case NAMED_OBJECT_PACKAGE
:
8540 return this->package_value()->location();
8544 // Export a named object.
8547 Named_object::export_named_object(Export
* exp
) const
8549 switch (this->classification_
)
8552 case NAMED_OBJECT_UNINITIALIZED
:
8553 case NAMED_OBJECT_UNKNOWN
:
8556 case NAMED_OBJECT_ERRONEOUS
:
8559 case NAMED_OBJECT_CONST
:
8560 this->const_value()->export_const(exp
, this->name_
);
8563 case NAMED_OBJECT_TYPE
:
8564 // Types are handled by export::write_types.
8567 case NAMED_OBJECT_TYPE_DECLARATION
:
8568 go_error_at(this->type_declaration_value()->location(),
8569 "attempt to export %<%s%> which was declared but not defined",
8570 this->message_name().c_str());
8573 case NAMED_OBJECT_FUNC_DECLARATION
:
8574 this->func_declaration_value()->export_func(exp
, this);
8577 case NAMED_OBJECT_VAR
:
8578 this->var_value()->export_var(exp
, this);
8581 case NAMED_OBJECT_RESULT_VAR
:
8582 case NAMED_OBJECT_SINK
:
8585 case NAMED_OBJECT_FUNC
:
8586 this->func_value()->export_func(exp
, this);
8591 // Convert a variable to the backend representation.
8594 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
8596 if (this->classification_
== NAMED_OBJECT_VAR
)
8597 return this->var_value()->get_backend_variable(gogo
, function
,
8598 this->package_
, this->name_
);
8599 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
8600 return this->result_var_value()->get_backend_variable(gogo
, function
,
8606 // Return the external identifier for this object.
8609 Named_object::get_id(Gogo
* gogo
)
8611 go_assert(!this->is_variable()
8612 && !this->is_result_variable()
8613 && !this->is_type());
8614 std::string decl_name
;
8615 if (this->is_function_declaration()
8616 && !this->func_declaration_value()->asm_name().empty())
8617 decl_name
= this->func_declaration_value()->asm_name();
8620 std::string package_name
;
8621 if (this->package_
== NULL
)
8622 package_name
= gogo
->package_name();
8624 package_name
= this->package_
->package_name();
8626 // Note that this will be misleading if this is an unexported
8627 // method generated for an embedded imported type. In that case
8628 // the unexported method should have the package name of the
8629 // package from which it is imported, but we are going to give
8630 // it our package name. Fixing this would require knowing the
8631 // package name, but we only know the package path. It might be
8632 // better to use package paths here anyhow. This doesn't affect
8633 // the assembler code, because we always set that name in
8634 // Function::get_or_make_decl anyhow. FIXME.
8636 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
8638 Function_type
* fntype
;
8639 if (this->is_function())
8640 fntype
= this->func_value()->type();
8641 else if (this->is_function_declaration())
8642 fntype
= this->func_declaration_value()->type();
8645 if (fntype
!= NULL
&& fntype
->is_method())
8647 decl_name
.push_back('.');
8648 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
8655 debug_go_named_object(Named_object
* no
)
8659 std::cerr
<< "<null>";
8662 std::cerr
<< "'" << no
->name() << "': ";
8664 switch (no
->classification())
8666 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8667 tag
= "uninitialized";
8669 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8672 case Named_object::NAMED_OBJECT_UNKNOWN
:
8675 case Named_object::NAMED_OBJECT_CONST
:
8678 case Named_object::NAMED_OBJECT_TYPE
:
8681 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8684 case Named_object::NAMED_OBJECT_VAR
:
8687 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8690 case Named_object::NAMED_OBJECT_SINK
:
8693 case Named_object::NAMED_OBJECT_FUNC
:
8696 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8699 case Named_object::NAMED_OBJECT_PACKAGE
:
8703 tag
= "<unknown named object classification>";
8706 std::cerr
<< tag
<< "\n";
8709 // Get the backend representation for this named object.
8712 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
8713 std::vector
<Btype
*>& type_decls
,
8714 std::vector
<Bfunction
*>& func_decls
)
8716 // If this is a definition, avoid trying to get the backend
8717 // representation, as that can crash.
8718 if (this->is_redefinition_
)
8720 go_assert(saw_errors());
8724 switch (this->classification_
)
8726 case NAMED_OBJECT_CONST
:
8727 if (!Gogo::is_erroneous_name(this->name_
))
8728 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
8731 case NAMED_OBJECT_TYPE
:
8733 Named_type
* named_type
= this->u_
.type_value
;
8735 // No need to do anything for aliases-- whatever has to be done
8736 // can be done for the alias target.
8737 if (named_type
->is_alias())
8740 if (!Gogo::is_erroneous_name(this->name_
))
8741 type_decls
.push_back(named_type
->get_backend(gogo
));
8743 // We need to produce a type descriptor for every named
8744 // type, and for a pointer to every named type, since
8745 // other files or packages might refer to them. We need
8746 // to do this even for hidden types, because they might
8747 // still be returned by some function. Simply calling the
8748 // type_descriptor method is enough to create the type
8749 // descriptor, even though we don't do anything with it.
8750 if (this->package_
== NULL
&& !saw_errors())
8753 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8754 named_type
->gc_symbol_pointer(gogo
);
8755 Type
* pn
= Type::make_pointer_type(named_type
);
8756 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8757 pn
->gc_symbol_pointer(gogo
);
8762 case NAMED_OBJECT_TYPE_DECLARATION
:
8763 go_error_at(Linemap::unknown_location(),
8764 "reference to undefined type %qs",
8765 this->message_name().c_str());
8768 case NAMED_OBJECT_VAR
:
8769 case NAMED_OBJECT_RESULT_VAR
:
8770 case NAMED_OBJECT_SINK
:
8773 case NAMED_OBJECT_FUNC
:
8775 Function
* func
= this->u_
.func_value
;
8776 if (!Gogo::is_erroneous_name(this->name_
))
8777 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
8779 if (func
->block() != NULL
)
8780 func
->build(gogo
, this);
8784 case NAMED_OBJECT_ERRONEOUS
:
8794 Bindings::Bindings(Bindings
* enclosing
)
8795 : enclosing_(enclosing
), named_objects_(), bindings_()
8802 Bindings::clear_file_scope(Gogo
* gogo
)
8804 Contour::iterator p
= this->bindings_
.begin();
8805 while (p
!= this->bindings_
.end())
8808 if (p
->second
->package() != NULL
)
8810 else if (p
->second
->is_package())
8812 else if (p
->second
->is_function()
8813 && !p
->second
->func_value()->type()->is_method()
8814 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
8823 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
8824 p
= this->bindings_
.erase(p
);
8829 // Look up a symbol.
8832 Bindings::lookup(const std::string
& name
) const
8834 Contour::const_iterator p
= this->bindings_
.find(name
);
8835 if (p
!= this->bindings_
.end())
8836 return p
->second
->resolve();
8837 else if (this->enclosing_
!= NULL
)
8838 return this->enclosing_
->lookup(name
);
8843 // Look up a symbol locally.
8846 Bindings::lookup_local(const std::string
& name
) const
8848 Contour::const_iterator p
= this->bindings_
.find(name
);
8849 if (p
== this->bindings_
.end())
8854 // Remove an object from a set of bindings. This is used for a
8855 // special case in thunks for functions which call recover.
8858 Bindings::remove_binding(Named_object
* no
)
8860 Contour::iterator pb
= this->bindings_
.find(no
->name());
8861 go_assert(pb
!= this->bindings_
.end());
8862 this->bindings_
.erase(pb
);
8863 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
8864 pn
!= this->named_objects_
.end();
8869 this->named_objects_
.erase(pn
);
8876 // Add a method to the list of objects. This is not added to the
8877 // lookup table. This is so that we have a single list of objects
8878 // declared at the top level, which we walk through when it's time to
8879 // convert to trees.
8882 Bindings::add_method(Named_object
* method
)
8884 this->named_objects_
.push_back(method
);
8887 // Add a generic Named_object to a Contour.
8890 Bindings::add_named_object_to_contour(Contour
* contour
,
8891 Named_object
* named_object
)
8893 go_assert(named_object
== named_object
->resolve());
8894 const std::string
& name(named_object
->name());
8895 go_assert(!Gogo::is_sink_name(name
));
8897 std::pair
<Contour::iterator
, bool> ins
=
8898 contour
->insert(std::make_pair(name
, named_object
));
8901 // The name was already there.
8902 if (named_object
->package() != NULL
8903 && ins
.first
->second
->package() == named_object
->package()
8904 && (ins
.first
->second
->classification()
8905 == named_object
->classification()))
8907 // This is a second import of the same object.
8908 return ins
.first
->second
;
8910 ins
.first
->second
= this->new_definition(ins
.first
->second
,
8912 return ins
.first
->second
;
8916 // Don't push declarations on the list. We push them on when
8917 // and if we find the definitions. That way we genericize the
8918 // functions in order.
8919 if (!named_object
->is_type_declaration()
8920 && !named_object
->is_function_declaration()
8921 && !named_object
->is_unknown())
8922 this->named_objects_
.push_back(named_object
);
8923 return named_object
;
8927 // We had an existing named object OLD_OBJECT, and we've seen a new
8928 // one NEW_OBJECT with the same name. FIXME: This does not free the
8929 // new object when we don't need it.
8932 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
8934 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
8938 switch (old_object
->classification())
8941 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8944 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8947 case Named_object::NAMED_OBJECT_UNKNOWN
:
8949 Named_object
* real
= old_object
->unknown_value()->real_named_object();
8951 return this->new_definition(real
, new_object
);
8952 go_assert(!new_object
->is_unknown());
8953 old_object
->unknown_value()->set_real_named_object(new_object
);
8954 if (!new_object
->is_type_declaration()
8955 && !new_object
->is_function_declaration())
8956 this->named_objects_
.push_back(new_object
);
8960 case Named_object::NAMED_OBJECT_CONST
:
8963 case Named_object::NAMED_OBJECT_TYPE
:
8964 if (new_object
->is_type_declaration())
8968 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8969 if (new_object
->is_type_declaration())
8971 if (new_object
->is_type())
8973 old_object
->set_type_value(new_object
->type_value());
8974 new_object
->type_value()->set_named_object(old_object
);
8975 this->named_objects_
.push_back(old_object
);
8980 case Named_object::NAMED_OBJECT_VAR
:
8981 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8982 // We have already given an error in the parser for cases where
8983 // one parameter or result variable redeclares another one.
8984 if ((new_object
->is_variable()
8985 && new_object
->var_value()->is_parameter())
8986 || new_object
->is_result_variable())
8990 case Named_object::NAMED_OBJECT_SINK
:
8993 case Named_object::NAMED_OBJECT_FUNC
:
8996 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8998 // We declare the hash and equality functions before defining
8999 // them, because we sometimes see that we need the declaration
9000 // while we are in the middle of a different function.
9002 // We declare the main function before the user defines it, to
9003 // give better error messages.
9005 // We declare inline functions before we define them, as we
9006 // only define them if we need them.
9007 if (new_object
->is_function()
9008 && ((Linemap::is_predeclared_location(old_object
->location())
9009 && Linemap::is_predeclared_location(new_object
->location()))
9010 || (Gogo::unpack_hidden_name(old_object
->name()) == "main"
9011 && Linemap::is_unknown_location(old_object
->location()))
9012 || (new_object
->package() != NULL
9013 && old_object
->func_declaration_value()->has_imported_body()
9014 && new_object
->func_value()->is_inline_only())))
9016 Function_type
* old_type
=
9017 old_object
->func_declaration_value()->type();
9018 Function_type
* new_type
= new_object
->func_value()->type();
9019 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
9021 Function_declaration
* fd
=
9022 old_object
->func_declaration_value();
9023 go_assert(fd
->asm_name().empty());
9024 old_object
->set_function_value(new_object
->func_value());
9025 this->named_objects_
.push_back(old_object
);
9032 case Named_object::NAMED_OBJECT_PACKAGE
:
9036 std::string n
= old_object
->message_name();
9038 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
9040 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
9042 old_object
->set_is_redefinition();
9043 new_object
->set_is_redefinition();
9045 if (!Linemap::is_unknown_location(old_object
->location())
9046 && !Linemap::is_predeclared_location(old_object
->location()))
9047 go_inform(old_object
->location(), "previous definition of %qs was here",
9053 // Add a named type.
9056 Bindings::add_named_type(Named_type
* named_type
)
9058 return this->add_named_object(named_type
->named_object());
9064 Bindings::add_function(const std::string
& name
, const Package
* package
,
9067 return this->add_named_object(Named_object::make_function(name
, package
,
9071 // Add a function declaration.
9074 Bindings::add_function_declaration(const std::string
& name
,
9075 const Package
* package
,
9076 Function_type
* type
,
9079 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
9081 return this->add_named_object(no
);
9084 // Define a type which was previously declared.
9087 Bindings::define_type(Named_object
* no
, Named_type
* type
)
9089 no
->set_type_value(type
);
9090 this->named_objects_
.push_back(no
);
9093 // Mark all local variables as used. This is used for some types of
9097 Bindings::mark_locals_used()
9099 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
9100 p
!= this->named_objects_
.end();
9102 if ((*p
)->is_variable())
9103 (*p
)->var_value()->set_is_used();
9106 // Traverse bindings.
9109 Bindings::traverse(Traverse
* traverse
, bool is_global
)
9111 unsigned int traverse_mask
= traverse
->traverse_mask();
9113 // We don't use an iterator because we permit the traversal to add
9114 // new global objects.
9115 const unsigned int e_or_t
= (Traverse::traverse_expressions
9116 | Traverse::traverse_types
);
9117 const unsigned int e_or_t_or_s
= (e_or_t
9118 | Traverse::traverse_statements
);
9119 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9121 Named_object
* p
= this->named_objects_
[i
];
9122 int t
= TRAVERSE_CONTINUE
;
9123 switch (p
->classification())
9125 case Named_object::NAMED_OBJECT_CONST
:
9126 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
9127 t
= traverse
->constant(p
, is_global
);
9128 if (t
== TRAVERSE_CONTINUE
9129 && (traverse_mask
& e_or_t
) != 0)
9131 Type
* tc
= p
->const_value()->type();
9133 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
9134 return TRAVERSE_EXIT
;
9135 t
= p
->const_value()->traverse_expression(traverse
);
9139 case Named_object::NAMED_OBJECT_VAR
:
9140 case Named_object::NAMED_OBJECT_RESULT_VAR
:
9141 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
9142 t
= traverse
->variable(p
);
9143 if (t
== TRAVERSE_CONTINUE
9144 && (traverse_mask
& e_or_t
) != 0)
9146 if (p
->is_result_variable()
9147 || p
->var_value()->has_type())
9149 Type
* tv
= (p
->is_variable()
9150 ? p
->var_value()->type()
9151 : p
->result_var_value()->type());
9153 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
9154 return TRAVERSE_EXIT
;
9157 if (t
== TRAVERSE_CONTINUE
9158 && (traverse_mask
& e_or_t_or_s
) != 0
9159 && p
->is_variable())
9160 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
9163 case Named_object::NAMED_OBJECT_FUNC
:
9164 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
9165 t
= traverse
->function(p
);
9167 if (t
== TRAVERSE_CONTINUE
9169 & (Traverse::traverse_variables
9170 | Traverse::traverse_constants
9171 | Traverse::traverse_functions
9172 | Traverse::traverse_blocks
9173 | Traverse::traverse_statements
9174 | Traverse::traverse_expressions
9175 | Traverse::traverse_types
)) != 0)
9176 t
= p
->func_value()->traverse(traverse
);
9179 case Named_object::NAMED_OBJECT_PACKAGE
:
9180 // These are traversed in Gogo::traverse.
9181 go_assert(is_global
);
9184 case Named_object::NAMED_OBJECT_TYPE
:
9185 if ((traverse_mask
& e_or_t
) != 0)
9186 t
= Type::traverse(p
->type_value(), traverse
);
9189 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
9190 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
9191 case Named_object::NAMED_OBJECT_UNKNOWN
:
9192 case Named_object::NAMED_OBJECT_ERRONEOUS
:
9195 case Named_object::NAMED_OBJECT_SINK
:
9200 if (t
== TRAVERSE_EXIT
)
9201 return TRAVERSE_EXIT
;
9204 // If we need to traverse types, check the function declarations,
9205 // which have types. Also check any methods of a type declaration.
9206 if ((traverse_mask
& e_or_t
) != 0)
9208 for (Bindings::const_declarations_iterator p
=
9209 this->begin_declarations();
9210 p
!= this->end_declarations();
9213 if (p
->second
->is_function_declaration())
9215 if (Type::traverse(p
->second
->func_declaration_value()->type(),
9218 return TRAVERSE_EXIT
;
9220 else if (p
->second
->is_type_declaration())
9222 const std::vector
<Named_object
*>* methods
=
9223 p
->second
->type_declaration_value()->methods();
9224 for (std::vector
<Named_object
*>::const_iterator pm
=
9226 pm
!= methods
->end();
9229 Named_object
* no
= *pm
;
9231 if (no
->is_function())
9232 t
= no
->func_value()->type();
9233 else if (no
->is_function_declaration())
9234 t
= no
->func_declaration_value()->type();
9237 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
9238 return TRAVERSE_EXIT
;
9244 // Traverse function declarations when needed.
9245 if ((traverse_mask
& Traverse::traverse_func_declarations
) != 0)
9247 for (Bindings::const_declarations_iterator p
= this->begin_declarations();
9248 p
!= this->end_declarations();
9251 if (p
->second
->is_function_declaration())
9253 if (traverse
->function_declaration(p
->second
) == TRAVERSE_EXIT
)
9254 return TRAVERSE_EXIT
;
9259 return TRAVERSE_CONTINUE
;
9263 Bindings::debug_dump()
9265 std::set
<Named_object
*> defs
;
9266 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9267 defs
.insert(this->named_objects_
[i
]);
9268 for (Contour::iterator p
= this->bindings_
.begin();
9269 p
!= this->bindings_
.end();
9272 const char* tag
= " ";
9273 if (defs
.find(p
->second
) != defs
.end())
9276 debug_go_named_object(p
->second
);
9281 debug_go_bindings(Bindings
* bindings
)
9283 if (bindings
!= NULL
)
9284 bindings
->debug_dump();
9289 // Clear any references to this label.
9294 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
9295 p
!= this->refs_
.end();
9298 this->refs_
.clear();
9301 // Get the backend representation for a label.
9304 Label::get_backend_label(Translate_context
* context
)
9306 if (this->blabel_
== NULL
)
9308 Function
* function
= context
->function()->func_value();
9309 Bfunction
* bfunction
= function
->get_decl();
9310 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
9313 return this->blabel_
;
9316 // Return an expression for the address of this label.
9319 Label::get_addr(Translate_context
* context
, Location location
)
9321 Blabel
* label
= this->get_backend_label(context
);
9322 return context
->backend()->label_address(label
, location
);
9325 // Return the dummy label that represents any instance of the blank label.
9328 Label::create_dummy_label()
9330 static Label
* dummy_label
;
9331 if (dummy_label
== NULL
)
9333 dummy_label
= new Label("_");
9334 dummy_label
->set_is_used();
9339 // Class Unnamed_label.
9341 // Get the backend representation for an unnamed label.
9344 Unnamed_label::get_blabel(Translate_context
* context
)
9346 if (this->blabel_
== NULL
)
9348 Function
* function
= context
->function()->func_value();
9349 Bfunction
* bfunction
= function
->get_decl();
9350 this->blabel_
= context
->backend()->label(bfunction
, "",
9353 return this->blabel_
;
9356 // Return a statement which defines this unnamed label.
9359 Unnamed_label::get_definition(Translate_context
* context
)
9361 Blabel
* blabel
= this->get_blabel(context
);
9362 return context
->backend()->label_definition_statement(blabel
);
9365 // Return a goto statement to this unnamed label.
9368 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
9370 Blabel
* blabel
= this->get_blabel(context
);
9371 return context
->backend()->goto_statement(blabel
, location
);
9376 Package::Package(const std::string
& pkgpath
,
9377 const std::string
& pkgpath_symbol
, Location location
)
9378 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
9379 package_name_(), bindings_(new Bindings(NULL
)),
9382 go_assert(!pkgpath
.empty());
9385 // Set the package name.
9388 Package::set_package_name(const std::string
& package_name
, Location location
)
9390 go_assert(!package_name
.empty());
9391 if (this->package_name_
.empty())
9392 this->package_name_
= package_name
;
9393 else if (this->package_name_
!= package_name
)
9394 go_error_at(location
,
9395 ("saw two different packages with "
9396 "the same package path %s: %s, %s"),
9397 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
9398 package_name
.c_str());
9401 // Return the pkgpath symbol, which is a prefix for symbols defined in
9405 Package::pkgpath_symbol() const
9407 if (this->pkgpath_symbol_
.empty())
9408 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
9409 return this->pkgpath_symbol_
;
9412 // Set the package path symbol.
9415 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
9417 go_assert(!pkgpath_symbol
.empty());
9418 if (this->pkgpath_symbol_
.empty())
9419 this->pkgpath_symbol_
= pkgpath_symbol
;
9421 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
9424 // Note that symbol from this package was and qualified by ALIAS.
9427 Package::note_usage(const std::string
& alias
) const
9429 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9430 go_assert(p
!= this->aliases_
.end());
9431 p
->second
->note_usage();
9434 // Forget a given usage. If forgetting this usage means this package becomes
9435 // unused, report that error.
9438 Package::forget_usage(Expression
* usage
) const
9440 if (this->fake_uses_
.empty())
9443 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
9444 go_assert(p
!= this->fake_uses_
.end());
9445 this->fake_uses_
.erase(p
);
9447 if (this->fake_uses_
.empty())
9448 go_error_at(this->location(), "imported and not used: %s",
9449 Gogo::message_name(this->package_name()).c_str());
9452 // Clear the used field for the next file. If the only usages of this package
9453 // are possibly fake, keep the fake usages for lowering.
9456 Package::clear_used()
9458 std::string dot_alias
= "." + this->package_name();
9459 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
9460 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
9461 this->fake_uses_
.clear();
9463 this->aliases_
.clear();
9467 Package::add_alias(const std::string
& alias
, Location location
)
9469 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9470 if (p
== this->aliases_
.end())
9472 std::pair
<Aliases::iterator
, bool> ret
;
9473 ret
= this->aliases_
.insert(std::make_pair(alias
,
9474 new Package_alias(location
)));
9480 // Determine types of constants. Everything else in a package
9481 // (variables, function declarations) should already have a fixed
9482 // type. Constants may have abstract types.
9485 Package::determine_types()
9487 Bindings
* bindings
= this->bindings_
;
9488 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
9489 p
!= bindings
->end_definitions();
9492 if ((*p
)->is_const())
9493 (*p
)->const_value()->determine_type();
9501 Traverse::~Traverse()
9503 if (this->types_seen_
!= NULL
)
9504 delete this->types_seen_
;
9505 if (this->expressions_seen_
!= NULL
)
9506 delete this->expressions_seen_
;
9509 // Record that we are looking at a type, and return true if we have
9513 Traverse::remember_type(const Type
* type
)
9515 if (type
->is_error_type())
9517 go_assert((this->traverse_mask() & traverse_types
) != 0
9518 || (this->traverse_mask() & traverse_expressions
) != 0);
9519 // We mostly only have to remember named types. But it turns out
9520 // that an interface type can refer to itself without using a name
9521 // by relying on interface inheritance, as in
9523 // type I interface { F() interface{I} }
9525 // Similarly it is possible for array types to refer to themselves
9526 // without a name, e.g.
9528 // var x [uintptr(unsafe.Sizeof(&x))]byte
9530 if (type
->classification() != Type::TYPE_NAMED
9531 && type
->classification() != Type::TYPE_ARRAY
9532 && type
->classification() != Type::TYPE_INTERFACE
)
9534 if (this->types_seen_
== NULL
)
9535 this->types_seen_
= new Types_seen();
9536 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
9540 // Record that we are looking at an expression, and return true if we
9541 // have already seen it. NB: this routine used to assert if the traverse
9542 // mask did not include expressions/types -- this is no longer the case,
9543 // since it can be useful to remember specific expressions during
9544 // walks that only cover statements.
9547 Traverse::remember_expression(const Expression
* expression
)
9549 if (this->expressions_seen_
== NULL
)
9550 this->expressions_seen_
= new Expressions_seen();
9551 std::pair
<Expressions_seen::iterator
, bool> ins
=
9552 this->expressions_seen_
->insert(expression
);
9556 // The default versions of these functions should never be called: the
9557 // traversal mask indicates which functions may be called.
9560 Traverse::variable(Named_object
*)
9566 Traverse::constant(Named_object
*, bool)
9572 Traverse::function(Named_object
*)
9578 Traverse::block(Block
*)
9584 Traverse::statement(Block
*, size_t*, Statement
*)
9590 Traverse::expression(Expression
**)
9596 Traverse::type(Type
*)
9602 Traverse::function_declaration(Named_object
*)
9607 // Class Statement_inserter.
9610 Statement_inserter::insert(Statement
* s
)
9612 if (this->statements_added_
!= NULL
)
9613 this->statements_added_
->insert(s
);
9615 if (this->block_
!= NULL
)
9617 go_assert(this->pindex_
!= NULL
);
9618 this->block_
->insert_statement_before(*this->pindex_
, s
);
9621 else if (this->var_
!= NULL
)
9622 this->var_
->add_preinit_statement(this->gogo_
, s
);
9624 go_assert(saw_errors());