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.
13 #include "go-optimize.h"
16 #include "statements.h"
17 #include "expressions.h"
27 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
32 globals_(new Bindings(NULL
)),
35 imported_unsafe_(false),
49 pkgpath_from_option_(false),
50 prefix_from_option_(false),
51 relative_import_path_(),
54 specific_type_functions_(),
55 specific_type_functions_are_written_(false),
56 named_types_are_converted_(false)
58 const Location loc
= Linemap::predeclared_location();
60 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
61 RUNTIME_TYPE_KIND_UINT8
);
62 this->add_named_type(uint8_type
);
63 this->add_named_type(Type::make_integer_type("uint16", true, 16,
64 RUNTIME_TYPE_KIND_UINT16
));
65 this->add_named_type(Type::make_integer_type("uint32", true, 32,
66 RUNTIME_TYPE_KIND_UINT32
));
67 this->add_named_type(Type::make_integer_type("uint64", true, 64,
68 RUNTIME_TYPE_KIND_UINT64
));
70 this->add_named_type(Type::make_integer_type("int8", false, 8,
71 RUNTIME_TYPE_KIND_INT8
));
72 this->add_named_type(Type::make_integer_type("int16", false, 16,
73 RUNTIME_TYPE_KIND_INT16
));
74 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
75 RUNTIME_TYPE_KIND_INT32
);
76 this->add_named_type(int32_type
);
77 this->add_named_type(Type::make_integer_type("int64", false, 64,
78 RUNTIME_TYPE_KIND_INT64
));
80 this->add_named_type(Type::make_float_type("float32", 32,
81 RUNTIME_TYPE_KIND_FLOAT32
));
82 this->add_named_type(Type::make_float_type("float64", 64,
83 RUNTIME_TYPE_KIND_FLOAT64
));
85 this->add_named_type(Type::make_complex_type("complex64", 64,
86 RUNTIME_TYPE_KIND_COMPLEX64
));
87 this->add_named_type(Type::make_complex_type("complex128", 128,
88 RUNTIME_TYPE_KIND_COMPLEX128
));
90 int int_type_size
= pointer_size
;
91 if (int_type_size
< 32)
93 this->add_named_type(Type::make_integer_type("uint", true,
95 RUNTIME_TYPE_KIND_UINT
));
96 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
97 RUNTIME_TYPE_KIND_INT
);
98 this->add_named_type(int_type
);
100 this->add_named_type(Type::make_integer_type("uintptr", true,
102 RUNTIME_TYPE_KIND_UINTPTR
));
104 // "byte" is an alias for "uint8".
105 uint8_type
->integer_type()->set_is_byte();
106 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
108 this->add_named_type(byte_type
->type_value());
110 // "rune" is an alias for "int32".
111 int32_type
->integer_type()->set_is_rune();
112 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
114 this->add_named_type(rune_type
->type_value());
116 this->add_named_type(Type::make_named_bool_type());
118 this->add_named_type(Type::make_named_string_type());
120 // "error" is interface { Error() string }.
122 Typed_identifier_list
*methods
= new Typed_identifier_list
;
123 Typed_identifier_list
*results
= new Typed_identifier_list
;
124 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
125 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
126 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
127 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
128 error_iface
->finalize_methods();
129 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
130 this->add_named_type(error_type
);
133 this->globals_
->add_constant(Typed_identifier("true",
134 Type::make_boolean_type(),
137 Expression::make_boolean(true, loc
),
139 this->globals_
->add_constant(Typed_identifier("false",
140 Type::make_boolean_type(),
143 Expression::make_boolean(false, loc
),
146 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
149 Expression::make_nil(loc
),
152 Type
* abstract_int_type
= Type::make_abstract_integer_type();
153 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
156 Expression::make_iota(),
159 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
160 new_type
->set_is_varargs();
161 new_type
->set_is_builtin();
162 Node::Escape_states
* new_escapes
=
163 new Node::Escape_states(1, Node::ESCAPE_NONE
);
164 new_type
->set_parameter_escape_states(new_escapes
);
165 new_type
->set_has_escape_info();
166 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
168 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
169 make_type
->set_is_varargs();
170 make_type
->set_is_builtin();
171 Node::Escape_states
* make_escapes
=
172 new Node::Escape_states(2, Node::ESCAPE_NONE
);
173 make_type
->set_parameter_escape_states(make_escapes
);
174 make_type
->set_has_escape_info();
175 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
177 Typed_identifier_list
* len_result
= new Typed_identifier_list();
178 len_result
->push_back(Typed_identifier("", int_type
, loc
));
179 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
181 len_type
->set_is_builtin();
182 Node::Escape_states
* len_escapes
=
183 new Node::Escape_states(1, Node::ESCAPE_NONE
);
184 len_type
->set_parameter_escape_states(len_escapes
);
185 len_type
->set_has_escape_info();
186 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
188 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
189 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
190 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
192 cap_type
->set_is_builtin();
193 Node::Escape_states
* cap_escapes
=
194 new Node::Escape_states(1, Node::ESCAPE_NONE
);
195 cap_type
->set_parameter_escape_states(cap_escapes
);
196 cap_type
->set_has_escape_info();
197 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
199 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
200 print_type
->set_is_varargs();
201 print_type
->set_is_builtin();
202 Node::Escape_states
* print_escapes
=
203 new Node::Escape_states(1, Node::ESCAPE_NONE
);
204 print_type
->set_parameter_escape_states(print_escapes
);
205 print_type
->set_has_escape_info();
206 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
208 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
209 print_type
->set_is_varargs();
210 print_type
->set_is_builtin();
211 print_type
->set_parameter_escape_states(print_escapes
);
212 print_type
->set_has_escape_info();
213 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
215 Type
*empty
= Type::make_empty_interface_type(loc
);
216 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
217 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
218 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
220 panic_type
->set_is_builtin();
221 Node::Escape_states
* panic_escapes
=
222 new Node::Escape_states(1, Node::ESCAPE_ARG
);
223 panic_type
->set_parameter_escape_states(panic_escapes
);
224 panic_type
->set_has_escape_info();
225 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
227 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
228 recover_result
->push_back(Typed_identifier("", empty
, loc
));
229 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
232 recover_type
->set_is_builtin();
233 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
235 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
236 close_type
->set_is_varargs();
237 close_type
->set_is_builtin();
238 Node::Escape_states
* close_escapes
=
239 new Node::Escape_states(1, Node::ESCAPE_NONE
);
240 close_type
->set_parameter_escape_states(close_escapes
);
241 close_type
->set_has_escape_info();
242 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
244 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
245 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
246 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
248 copy_type
->set_is_varargs();
249 copy_type
->set_is_builtin();
250 Node::Escape_states
* copy_escapes
=
251 new Node::Escape_states(2, Node::ESCAPE_NONE
);
252 copy_type
->set_parameter_escape_states(copy_escapes
);
253 copy_type
->set_has_escape_info();
254 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
256 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
257 append_type
->set_is_varargs();
258 append_type
->set_is_builtin();
259 Node::Escape_states
* append_escapes
= new Node::Escape_states
;
260 append_escapes
->push_back(Node::ESCAPE_ARG
);
261 append_escapes
->push_back(Node::ESCAPE_NONE
);
262 append_type
->set_parameter_escape_states(append_escapes
);
263 append_type
->set_has_escape_info();
264 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
266 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
267 complex_type
->set_is_varargs();
268 complex_type
->set_is_builtin();
269 Node::Escape_states
* complex_escapes
=
270 new Node::Escape_states(2, Node::ESCAPE_NONE
);
271 complex_type
->set_parameter_escape_states(complex_escapes
);
272 complex_type
->set_has_escape_info();
273 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
275 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
276 real_type
->set_is_varargs();
277 real_type
->set_is_builtin();
278 Node::Escape_states
* real_escapes
=
279 new Node::Escape_states(1, Node::ESCAPE_NONE
);
280 real_type
->set_parameter_escape_states(real_escapes
);
281 real_type
->set_has_escape_info();
282 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
284 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
285 imag_type
->set_is_varargs();
286 imag_type
->set_is_builtin();
287 Node::Escape_states
* imag_escapes
=
288 new Node::Escape_states(1, Node::ESCAPE_NONE
);
289 imag_type
->set_parameter_escape_states(imag_escapes
);
290 imag_type
->set_has_escape_info();
291 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
293 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
294 delete_type
->set_is_varargs();
295 delete_type
->set_is_builtin();
296 Node::Escape_states
* delete_escapes
=
297 new Node::Escape_states(2, Node::ESCAPE_NONE
);
298 delete_type
->set_parameter_escape_states(delete_escapes
);
299 delete_type
->set_has_escape_info();
300 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
303 // Convert a pkgpath into a string suitable for a symbol. Note that
304 // this transformation is convenient but imperfect. A -fgo-pkgpath
305 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
306 // possibly leading to link time errors.
309 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
311 std::string s
= pkgpath
;
312 for (size_t i
= 0; i
< s
.length(); ++i
)
315 if ((c
>= 'a' && c
<= 'z')
316 || (c
>= 'A' && c
<= 'Z')
317 || (c
>= '0' && c
<= '9'))
325 // Get the package path to use for type reflection data. This should
326 // ideally be unique across the entire link.
329 Gogo::pkgpath() const
331 go_assert(this->pkgpath_set_
);
332 return this->pkgpath_
;
335 // Set the package path from the -fgo-pkgpath command line option.
338 Gogo::set_pkgpath(const std::string
& arg
)
340 go_assert(!this->pkgpath_set_
);
341 this->pkgpath_
= arg
;
342 this->pkgpath_set_
= true;
343 this->pkgpath_from_option_
= true;
346 // Get the package path to use for symbol names.
349 Gogo::pkgpath_symbol() const
351 go_assert(this->pkgpath_set_
);
352 return this->pkgpath_symbol_
;
355 // Set the unique prefix to use to determine the package path, from
356 // the -fgo-prefix command line option.
359 Gogo::set_prefix(const std::string
& arg
)
361 go_assert(!this->prefix_from_option_
);
363 this->prefix_from_option_
= true;
366 // Munge name for use in an error message.
369 Gogo::message_name(const std::string
& name
)
371 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
374 // Get the package name.
377 Gogo::package_name() const
379 go_assert(this->package_
!= NULL
);
380 return this->package_
->package_name();
383 // Set the package name.
386 Gogo::set_package_name(const std::string
& package_name
,
389 if (this->package_
!= NULL
)
391 if (this->package_
->package_name() != package_name
)
392 error_at(location
, "expected package %<%s%>",
393 Gogo::message_name(this->package_
->package_name()).c_str());
397 // Now that we know the name of the package we are compiling, set
398 // the package path to use for reflect.Type.PkgPath and global
400 if (this->pkgpath_set_
)
401 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
404 if (!this->prefix_from_option_
&& package_name
== "main")
406 this->pkgpath_
= package_name
;
407 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
411 if (!this->prefix_from_option_
)
412 this->prefix_
= "go";
413 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
414 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
415 + Gogo::pkgpath_for_symbol(package_name
));
417 this->pkgpath_set_
= true;
420 this->package_
= this->register_package(this->pkgpath_
,
421 this->pkgpath_symbol_
, location
);
422 this->package_
->set_package_name(package_name
, location
);
424 if (this->is_main_package())
426 // Declare "main" as a function which takes no parameters and
428 Location uloc
= Linemap::unknown_location();
429 this->declare_function(Gogo::pack_hidden_name("main", false),
430 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
435 // Return whether this is the "main" package. This is not true if
436 // -fgo-pkgpath or -fgo-prefix was used.
439 Gogo::is_main_package() const
441 return (this->package_name() == "main"
442 && !this->pkgpath_from_option_
443 && !this->prefix_from_option_
);
449 Gogo::import_package(const std::string
& filename
,
450 const std::string
& local_name
,
451 bool is_local_name_exported
,
454 if (filename
.empty())
456 error_at(location
, "import path is empty");
460 const char *pf
= filename
.data();
461 const char *pend
= pf
+ filename
.length();
465 int adv
= Lex::fetch_char(pf
, &c
);
468 error_at(location
, "import path contains invalid UTF-8 sequence");
473 error_at(location
, "import path contains NUL");
476 if (c
< 0x20 || c
== 0x7f)
478 error_at(location
, "import path contains control character");
483 error_at(location
, "import path contains backslash; use slash");
486 if (Lex::is_unicode_space(c
))
488 error_at(location
, "import path contains space character");
491 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
493 error_at(location
, "import path contains invalid character '%c'", c
);
499 if (IS_ABSOLUTE_PATH(filename
.c_str()))
501 error_at(location
, "import path cannot be absolute path");
505 if (local_name
== "init")
506 error_at(location
, "cannot import package as init");
508 if (filename
== "unsafe")
510 this->import_unsafe(local_name
, is_local_name_exported
, location
);
514 Imports::const_iterator p
= this->imports_
.find(filename
);
515 if (p
!= this->imports_
.end())
517 Package
* package
= p
->second
;
518 package
->set_location(location
);
519 package
->set_is_imported();
520 std::string ln
= local_name
;
521 bool is_ln_exported
= is_local_name_exported
;
524 ln
= package
->package_name();
525 go_assert(!ln
.empty());
526 is_ln_exported
= Lex::is_exported_name(ln
);
530 Bindings
* bindings
= package
->bindings();
531 for (Bindings::const_declarations_iterator p
=
532 bindings
->begin_declarations();
533 p
!= bindings
->end_declarations();
535 this->add_dot_import_object(p
->second
);
538 package
->set_uses_sink_alias();
541 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
542 this->package_
->bindings()->add_package(ln
, package
);
547 Import::Stream
* stream
= Import::open_package(filename
, location
,
548 this->relative_import_path_
);
551 error_at(location
, "import file %qs not found", filename
.c_str());
555 Import
imp(stream
, location
);
556 imp
.register_builtin_types(this);
557 Package
* package
= imp
.import(this, local_name
, is_local_name_exported
);
560 if (package
->pkgpath() == this->pkgpath())
562 ("imported package uses same package path as package "
563 "being compiled (see -fgo-pkgpath option)"));
565 this->imports_
.insert(std::make_pair(filename
, package
));
566 package
->set_is_imported();
572 // Add an import control function for an imported package to the list.
575 Gogo::add_import_init_fn(const std::string
& package_name
,
576 const std::string
& init_name
, int prio
)
578 for (std::set
<Import_init
>::const_iterator p
=
579 this->imported_init_fns_
.begin();
580 p
!= this->imported_init_fns_
.end();
583 if (p
->init_name() == init_name
)
585 // If a test of package P1, built as part of package P1,
586 // imports package P2, and P2 imports P1 (perhaps
587 // indirectly), then we will see the same import name with
588 // different import priorities. That is OK, so don't give
589 // an error about it.
590 if (p
->package_name() != package_name
)
592 error("duplicate package initialization name %qs",
593 Gogo::message_name(init_name
).c_str());
594 inform(UNKNOWN_LOCATION
, "used by package %qs at priority %d",
595 Gogo::message_name(p
->package_name()).c_str(),
597 inform(UNKNOWN_LOCATION
, " and by package %qs at priority %d",
598 Gogo::message_name(package_name
).c_str(), prio
);
604 this->imported_init_fns_
.insert(Import_init(package_name
, init_name
,
608 // Return whether we are at the global binding level.
611 Gogo::in_global_scope() const
613 return this->functions_
.empty();
616 // Return the current binding contour.
619 Gogo::current_bindings()
621 if (!this->functions_
.empty())
622 return this->functions_
.back().blocks
.back()->bindings();
623 else if (this->package_
!= NULL
)
624 return this->package_
->bindings();
626 return this->globals_
;
630 Gogo::current_bindings() const
632 if (!this->functions_
.empty())
633 return this->functions_
.back().blocks
.back()->bindings();
634 else if (this->package_
!= NULL
)
635 return this->package_
->bindings();
637 return this->globals_
;
640 // Return the special variable used as the zero value of types.
643 Gogo::zero_value(Type
*type
)
645 if (this->zero_value_
== NULL
)
647 Location bloc
= Linemap::predeclared_location();
649 // We will change the type later, when we know the size.
650 Type
* byte_type
= this->lookup_global("byte")->type_value();
652 Expression
* zero
= Expression::make_integer_ul(0, NULL
, bloc
);
653 Type
* array_type
= Type::make_array_type(byte_type
, zero
);
655 Variable
* var
= new Variable(array_type
, NULL
, true, false, false, bloc
);
656 this->zero_value_
= Named_object::make_variable("go$zerovalue", NULL
,
660 // The zero value will be the maximum required size.
662 bool ok
= type
->backend_type_size(this, &size
);
664 go_assert(saw_errors());
667 if (size
> this->zero_value_size_
)
668 this->zero_value_size_
= size
;
671 ok
= type
->backend_type_align(this, &align
);
673 go_assert(saw_errors());
676 if (align
> this->zero_value_align_
)
677 this->zero_value_align_
= align
;
679 return this->zero_value_
;
682 // Return whether V is the zero value variable.
685 Gogo::is_zero_value(Variable
* v
) const
687 return this->zero_value_
!= NULL
&& this->zero_value_
->var_value() == v
;
690 // Return the backend variable for the special zero value, or NULL if
694 Gogo::backend_zero_value()
696 if (this->zero_value_
== NULL
)
699 Type
* byte_type
= this->lookup_global("byte")->type_value();
700 Btype
* bbtype_type
= byte_type
->get_backend(this);
702 Type
* int_type
= this->lookup_global("int")->type_value();
704 Expression
* e
= Expression::make_integer_int64(this->zero_value_size_
,
706 Linemap::unknown_location());
707 Translate_context
context(this, NULL
, NULL
, NULL
);
708 Bexpression
* blength
= e
->get_backend(&context
);
710 Btype
* barray_type
= this->backend()->array_type(bbtype_type
, blength
);
712 std::string zname
= this->zero_value_
->name();
714 this->backend()->implicit_variable(zname
, barray_type
, false,
715 true, true, this->zero_value_align_
);
716 this->backend()->implicit_variable_set_init(zvar
, zname
, barray_type
,
717 false, true, true, NULL
);
721 // Add statements to INIT_STMTS which run the initialization
722 // functions for imported packages. This is only used for the "main"
726 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
)
728 go_assert(this->is_main_package());
730 if (this->imported_init_fns_
.empty())
733 Location unknown_loc
= Linemap::unknown_location();
734 Function_type
* func_type
=
735 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
736 Btype
* fntype
= func_type
->get_backend_fntype(this);
738 // We must call them in increasing priority order.
739 std::vector
<Import_init
> v
;
740 for (std::set
<Import_init
>::const_iterator p
=
741 this->imported_init_fns_
.begin();
742 p
!= this->imported_init_fns_
.end();
745 std::sort(v
.begin(), v
.end());
747 // We build calls to the init functions, which take no arguments.
748 std::vector
<Bexpression
*> empty_args
;
749 for (std::vector
<Import_init
>::const_iterator p
= v
.begin();
753 std::string user_name
= p
->package_name() + ".init";
754 const std::string
& init_name(p
->init_name());
756 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
757 true, true, true, false,
759 Bexpression
* pfunc_code
=
760 this->backend()->function_code_expression(pfunc
, unknown_loc
);
761 Bexpression
* pfunc_call
=
762 this->backend()->call_expression(pfunc_code
, empty_args
,
764 init_stmts
.push_back(this->backend()->expression_statement(pfunc_call
));
768 // Register global variables with the garbage collector. We need to
769 // register all variables which can hold a pointer value. They become
770 // roots during the mark phase. We build a struct that is easy to
771 // hook into a list of roots.
773 // struct __go_gc_root_list
775 // struct __go_gc_root_list* __next;
776 // struct __go_gc_root
783 // The last entry in the roots array has a NULL decl field.
786 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
787 std::vector
<Bstatement
*>& init_stmts
)
792 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
793 Type
* uint_type
= Type::lookup_integer_type("uint");
794 Struct_type
* root_type
= Type::make_builtin_struct_type(2,
796 "__size", uint_type
);
798 Location builtin_loc
= Linemap::predeclared_location();
799 Expression
* length
= Expression::make_integer_ul(var_gc
.size(), NULL
,
802 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
803 Type
* ptdt
= Type::make_type_descriptor_ptr_type();
804 Struct_type
* root_list_type
=
805 Type::make_builtin_struct_type(2,
807 "__roots", root_array_type
);
809 // Build an initializer for the __roots array.
811 Expression_list
* roots_init
= new Expression_list();
814 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
818 Expression_list
* init
= new Expression_list();
820 Location no_loc
= (*p
)->location();
821 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
822 Expression
* decl_addr
=
823 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
824 init
->push_back(decl_addr
);
826 Expression
* decl_size
=
827 Expression::make_type_info(decl
->type(), Expression::TYPE_INFO_SIZE
);
828 init
->push_back(decl_size
);
830 Expression
* root_ctor
=
831 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
832 roots_init
->push_back(root_ctor
);
835 // The list ends with a NULL entry.
837 Expression_list
* null_init
= new Expression_list();
838 Expression
* nil
= Expression::make_nil(builtin_loc
);
839 null_init
->push_back(nil
);
841 Expression
*zero
= Expression::make_integer_ul(0, NULL
, builtin_loc
);
842 null_init
->push_back(zero
);
844 Expression
* null_root_ctor
=
845 Expression::make_struct_composite_literal(root_type
, null_init
,
847 roots_init
->push_back(null_root_ctor
);
849 // Build a constructor for the struct.
851 Expression_list
* root_list_init
= new Expression_list();
852 root_list_init
->push_back(nil
);
854 Expression
* roots_ctor
=
855 Expression::make_array_composite_literal(root_array_type
, roots_init
,
857 root_list_init
->push_back(roots_ctor
);
859 Expression
* root_list_ctor
=
860 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
863 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
865 root_addr
->unary_expression()->set_is_gc_root();
866 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
867 builtin_loc
, 1, root_addr
);
869 Translate_context
context(this, NULL
, NULL
, NULL
);
870 Bexpression
* bcall
= register_roots
->get_backend(&context
);
871 init_stmts
.push_back(this->backend()->expression_statement(bcall
));
874 // Get the name to use for the import control function. If there is a
875 // global function or variable, then we know that that name must be
876 // unique in the link, and we use it as the basis for our name.
879 Gogo::get_init_fn_name()
881 if (this->init_fn_name_
.empty())
883 go_assert(this->package_
!= NULL
);
884 if (this->is_main_package())
886 // Use a name which the runtime knows.
887 this->init_fn_name_
= "__go_init_main";
891 std::string s
= this->pkgpath_symbol();
892 s
.append("..import");
893 this->init_fn_name_
= s
;
897 return this->init_fn_name_
;
900 // Build the decl for the initialization function.
903 Gogo::initialization_function_decl()
905 std::string name
= this->get_init_fn_name();
906 Location loc
= this->package_
->location();
908 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
909 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
910 return Named_object::make_function(name
, NULL
, initfn
);
913 // Create the magic initialization function. CODE_STMT is the
914 // code that it needs to run.
917 Gogo::create_initialization_function(Named_object
* initfn
,
918 Bstatement
* code_stmt
)
920 // Make sure that we thought we needed an initialization function,
921 // as otherwise we will not have reported it in the export data.
922 go_assert(this->is_main_package() || this->need_init_fn_
);
925 initfn
= this->initialization_function_decl();
927 // Bind the initialization function code to a block.
928 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
929 Location pkg_loc
= this->package_
->location();
930 std::vector
<Bvariable
*> vars
;
931 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
933 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
935 go_assert(saw_errors());
941 // Search for references to VAR in any statements or called functions.
943 class Find_var
: public Traverse
946 // A hash table we use to avoid looping. The index is the name of a
947 // named object. We only look through objects defined in this
949 typedef Unordered_set(const void*) Seen_objects
;
951 Find_var(Named_object
* var
, Seen_objects
* seen_objects
)
952 : Traverse(traverse_expressions
),
953 var_(var
), seen_objects_(seen_objects
), found_(false)
956 // Whether the variable was found.
959 { return this->found_
; }
962 expression(Expression
**);
965 // The variable we are looking for.
967 // Names of objects we have already seen.
968 Seen_objects
* seen_objects_
;
969 // True if the variable was found.
973 // See if EXPR refers to VAR, looking through function calls and
974 // variable initializations.
977 Find_var::expression(Expression
** pexpr
)
979 Expression
* e
= *pexpr
;
981 Var_expression
* ve
= e
->var_expression();
984 Named_object
* v
= ve
->named_object();
988 return TRAVERSE_EXIT
;
991 if (v
->is_variable() && v
->package() == NULL
)
993 Expression
* init
= v
->var_value()->init();
996 std::pair
<Seen_objects::iterator
, bool> ins
=
997 this->seen_objects_
->insert(v
);
1000 // This is the first time we have seen this name.
1001 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1002 return TRAVERSE_EXIT
;
1008 // We traverse the code of any function or bound method we see. Note that
1009 // this means that we will traverse the code of a function or bound method
1010 // whose address is taken even if it is not called.
1011 Func_expression
* fe
= e
->func_expression();
1012 Bound_method_expression
* bme
= e
->bound_method_expression();
1013 if (fe
!= NULL
|| bme
!= NULL
)
1015 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1016 if (f
->is_function() && f
->package() == NULL
)
1018 std::pair
<Seen_objects::iterator
, bool> ins
=
1019 this->seen_objects_
->insert(f
);
1022 // This is the first time we have seen this name.
1023 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
1024 return TRAVERSE_EXIT
;
1029 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1032 Temporary_statement
* ts
= tre
->statement();
1033 Expression
* init
= ts
->init();
1036 std::pair
<Seen_objects::iterator
, bool> ins
=
1037 this->seen_objects_
->insert(ts
);
1040 // This is the first time we have seen this temporary
1042 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1043 return TRAVERSE_EXIT
;
1048 return TRAVERSE_CONTINUE
;
1051 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1054 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1057 Find_var::Seen_objects seen_objects
;
1058 Find_var
find_var(var
, &seen_objects
);
1060 Expression::traverse(&expr
, &find_var
);
1061 if (preinit
!= NULL
)
1062 preinit
->traverse(&find_var
);
1065 Expression
* init
= dep
->var_value()->init();
1067 Expression::traverse(&init
, &find_var
);
1068 if (dep
->var_value()->has_pre_init())
1069 dep
->var_value()->preinit()->traverse(&find_var
);
1072 return find_var
.found();
1075 // Sort variable initializations. If the initialization expression
1076 // for variable A refers directly or indirectly to the initialization
1077 // expression for variable B, then we must initialize B before A.
1083 : var_(NULL
), init_(NULL
), dep_count_(0)
1086 Var_init(Named_object
* var
, Bstatement
* init
)
1087 : var_(var
), init_(init
), dep_count_(0)
1090 // Return the variable.
1093 { return this->var_
; }
1095 // Return the initialization expression.
1098 { return this->init_
; }
1100 // Return the number of remaining dependencies.
1103 { return this->dep_count_
; }
1105 // Increment the number of dependencies.
1108 { ++this->dep_count_
; }
1110 // Decrement the number of dependencies.
1113 { --this->dep_count_
; }
1116 // The variable being initialized.
1118 // The initialization statement.
1120 // The number of initializations this is dependent on. A variable
1121 // initialization should not be emitted if any of its dependencies
1122 // have not yet been resolved.
1126 // For comparing Var_init keys in a map.
1129 operator<(const Var_init
& v1
, const Var_init
& v2
)
1130 { return v1
.var()->name() < v2
.var()->name(); }
1132 typedef std::list
<Var_init
> Var_inits
;
1134 // Sort the variable initializations. The rule we follow is that we
1135 // emit them in the order they appear in the array, except that if the
1136 // initialization expression for a variable V1 depends upon another
1137 // variable V2 then we initialize V1 after V2.
1140 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1142 if (var_inits
->empty())
1145 typedef std::pair
<Named_object
*, Named_object
*> No_no
;
1146 typedef std::map
<No_no
, bool> Cache
;
1149 // A mapping from a variable initialization to a set of
1150 // variable initializations that depend on it.
1151 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1152 Init_deps init_deps
;
1153 bool init_loop
= false;
1154 for (Var_inits::iterator p1
= var_inits
->begin();
1155 p1
!= var_inits
->end();
1158 Named_object
* var
= p1
->var();
1159 Expression
* init
= var
->var_value()->init();
1160 Block
* preinit
= var
->var_value()->preinit();
1161 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1163 // Start walking through the list to see which variables VAR
1164 // needs to wait for.
1165 for (Var_inits::iterator p2
= var_inits
->begin();
1166 p2
!= var_inits
->end();
1169 if (var
== p2
->var())
1172 Named_object
* p2var
= p2
->var();
1173 No_no
key(var
, p2var
);
1174 std::pair
<Cache::iterator
, bool> ins
=
1175 cache
.insert(std::make_pair(key
, false));
1177 ins
.first
->second
= expression_requires(init
, preinit
, dep
, p2var
);
1178 if (ins
.first
->second
)
1180 // VAR depends on P2VAR.
1181 init_deps
[*p2
].insert(&(*p1
));
1182 p1
->add_dependency();
1184 // Check for cycles.
1185 key
= std::make_pair(p2var
, var
);
1186 ins
= cache
.insert(std::make_pair(key
, false));
1189 expression_requires(p2var
->var_value()->init(),
1190 p2var
->var_value()->preinit(),
1191 gogo
->var_depends_on(p2var
->var_value()),
1193 if (ins
.first
->second
)
1195 error_at(var
->location(),
1196 ("initialization expressions for %qs and "
1197 "%qs depend upon each other"),
1198 var
->message_name().c_str(),
1199 p2var
->message_name().c_str());
1200 inform(p2
->var()->location(), "%qs defined here",
1201 p2var
->message_name().c_str());
1209 // If there are no dependencies then the declaration order is sorted.
1210 if (!init_deps
.empty() && !init_loop
)
1212 // Otherwise, sort variable initializations by emitting all variables with
1213 // no dependencies in declaration order. VAR_INITS is already in
1214 // declaration order.
1216 while (!var_inits
->empty())
1218 Var_inits::iterator v1
;;
1219 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1221 if (v1
->dep_count() == 0)
1224 go_assert(v1
!= var_inits
->end());
1226 // V1 either has no dependencies or its dependencies have already
1227 // been emitted, add it to READY next. When V1 is emitted, remove
1228 // a dependency from each V that depends on V1.
1229 ready
.splice(ready
.end(), *var_inits
, v1
);
1231 Init_deps::iterator p1
= init_deps
.find(*v1
);
1232 if (p1
!= init_deps
.end())
1234 std::set
<Var_init
*> resolved
= p1
->second
;
1235 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1236 pv
!= resolved
.end();
1238 (*pv
)->remove_dependency();
1239 init_deps
.erase(p1
);
1242 var_inits
->swap(ready
);
1243 go_assert(init_deps
.empty());
1246 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1247 // check for a loop of VAR on itself. We only do this if
1248 // INIT is not NULL and there is no dependency; when INIT is
1249 // NULL, it means that PREINIT sets VAR, which we will
1250 // interpret as a loop.
1251 for (Var_inits::const_iterator p
= var_inits
->begin();
1252 p
!= var_inits
->end();
1255 Named_object
* var
= p
->var();
1256 Expression
* init
= var
->var_value()->init();
1257 Block
* preinit
= var
->var_value()->preinit();
1258 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1259 if (init
!= NULL
&& dep
== NULL
1260 && expression_requires(init
, preinit
, NULL
, var
))
1261 error_at(var
->location(),
1262 "initialization expression for %qs depends upon itself",
1263 var
->message_name().c_str());
1267 // Write out the global definitions.
1270 Gogo::write_globals()
1272 this->build_interface_method_tables();
1274 Bindings
* bindings
= this->current_bindings();
1276 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1277 p
!= bindings
->end_declarations();
1280 // If any function declarations needed a descriptor, make sure
1282 Named_object
* no
= p
->second
;
1283 if (no
->is_function_declaration())
1284 no
->func_declaration_value()->build_backend_descriptor(this);
1287 // Lists of globally declared types, variables, constants, and functions
1288 // that must be defined.
1289 std::vector
<Btype
*> type_decls
;
1290 std::vector
<Bvariable
*> var_decls
;
1291 std::vector
<Bexpression
*> const_decls
;
1292 std::vector
<Bfunction
*> func_decls
;
1294 // The init function declaration, if necessary.
1295 Named_object
* init_fndecl
= NULL
;
1297 std::vector
<Bstatement
*> init_stmts
;
1298 std::vector
<Bstatement
*> var_init_stmts
;
1300 if (this->is_main_package())
1301 this->init_imports(init_stmts
);
1303 // A list of variable initializations.
1304 Var_inits var_inits
;
1306 // A list of variables which need to be registered with the garbage
1308 size_t count_definitions
= bindings
->size_definitions();
1309 std::vector
<Named_object
*> var_gc
;
1310 var_gc
.reserve(count_definitions
);
1312 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1313 p
!= bindings
->end_definitions();
1316 Named_object
* no
= *p
;
1317 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1319 // There is nothing to do for a package.
1320 if (no
->is_package())
1323 // There is nothing to do for an object which was imported from
1324 // a different package into the global scope.
1325 if (no
->package() != NULL
)
1328 // Skip blank named functions and constants.
1329 if ((no
->is_function() && no
->func_value()->is_sink())
1330 || (no
->is_const() && no
->const_value()->is_sink()))
1333 // There is nothing useful we can output for constants which
1334 // have ideal or non-integral type.
1337 Type
* type
= no
->const_value()->type();
1339 type
= no
->const_value()->expr()->type();
1340 if (type
->is_abstract() || !type
->is_numeric_type())
1344 if (!no
->is_variable())
1345 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1348 Variable
* var
= no
->var_value();
1349 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1350 var_decls
.push_back(bvar
);
1352 // Check for a sink variable, which may be used to run an
1353 // initializer purely for its side effects.
1354 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1356 Bstatement
* var_init_stmt
= NULL
;
1357 if (!var
->has_pre_init())
1359 // If the backend representation of the variable initializer is
1360 // constant, we can just set the initial value using
1361 // global_var_set_init instead of during the init() function.
1362 // The initializer is constant if it is the zero-value of the
1363 // variable's type or if the initial value is an immutable value
1364 // that is not copied to the heap.
1365 bool is_constant_initializer
= false;
1366 if (var
->init() == NULL
)
1367 is_constant_initializer
= true;
1370 Type
* var_type
= var
->type();
1371 Expression
* init
= var
->init();
1372 Expression
* init_cast
=
1373 Expression::make_cast(var_type
, init
, var
->location());
1374 is_constant_initializer
=
1375 init_cast
->is_immutable() && !var_type
->has_pointer();
1378 // Non-constant variable initializations might need to create
1379 // temporary variables, which will need the initialization
1380 // function as context.
1381 if (!is_constant_initializer
&& init_fndecl
== NULL
)
1382 init_fndecl
= this->initialization_function_decl();
1383 Bexpression
* var_binit
= var
->get_init(this, init_fndecl
);
1385 if (var_binit
== NULL
)
1387 else if (is_constant_initializer
)
1389 if (expression_requires(var
->init(), NULL
,
1390 this->var_depends_on(var
), no
))
1391 error_at(no
->location(),
1392 "initialization expression for %qs depends "
1394 no
->message_name().c_str());
1395 this->backend()->global_variable_set_init(bvar
, var_binit
);
1399 this->backend()->expression_statement(var_binit
);
1402 Location loc
= var
->location();
1403 Bexpression
* var_expr
=
1404 this->backend()->var_expression(bvar
, loc
);
1406 this->backend()->assignment_statement(var_expr
, var_binit
,
1412 // We are going to create temporary variables which
1413 // means that we need an fndecl.
1414 if (init_fndecl
== NULL
)
1415 init_fndecl
= this->initialization_function_decl();
1417 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1418 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1421 if (var_init_stmt
!= NULL
)
1423 if (var
->init() == NULL
&& !var
->has_pre_init())
1424 var_init_stmts
.push_back(var_init_stmt
);
1426 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1428 else if (this->var_depends_on(var
) != NULL
)
1430 // This variable is initialized from something that is
1431 // not in its init or preinit. This variable needs to
1432 // participate in dependency analysis sorting, in case
1433 // some other variable depends on this one.
1434 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1435 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1436 Bstatement
* zero_stmt
=
1437 this->backend()->expression_statement(zero
);
1438 var_inits
.push_back(Var_init(no
, zero_stmt
));
1441 if (!is_sink
&& var
->type()->has_pointer())
1442 var_gc
.push_back(no
);
1446 // Register global variables with the garbage collector.
1447 this->register_gc_vars(var_gc
, init_stmts
);
1449 // Simple variable initializations, after all variables are
1451 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1453 // Complete variable initializations, first sorting them into a
1455 if (!var_inits
.empty())
1457 sort_var_inits(this, &var_inits
);
1458 for (Var_inits::const_iterator p
= var_inits
.begin();
1459 p
!= var_inits
.end();
1461 init_stmts
.push_back(p
->init());
1464 // After all the variables are initialized, call the init
1465 // functions if there are any. Init functions take no arguments, so
1466 // we pass in EMPTY_ARGS to call them.
1467 std::vector
<Bexpression
*> empty_args
;
1468 for (std::vector
<Named_object
*>::const_iterator p
=
1469 this->init_functions_
.begin();
1470 p
!= this->init_functions_
.end();
1473 Location func_loc
= (*p
)->location();
1474 Function
* func
= (*p
)->func_value();
1475 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1476 Bexpression
* func_code
=
1477 this->backend()->function_code_expression(initfn
, func_loc
);
1478 Bexpression
* call
= this->backend()->call_expression(func_code
,
1481 init_stmts
.push_back(this->backend()->expression_statement(call
));
1484 // Set up a magic function to do all the initialization actions.
1485 // This will be called if this package is imported.
1486 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1487 if (this->need_init_fn_
|| this->is_main_package())
1490 this->create_initialization_function(init_fndecl
, init_fncode
);
1491 if (init_fndecl
!= NULL
)
1492 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1495 // We should not have seen any new bindings created during the conversion.
1496 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1498 // Define all globally declared values.
1500 this->backend()->write_global_definitions(type_decls
, const_decls
,
1501 func_decls
, var_decls
);
1504 // Return the current block.
1507 Gogo::current_block()
1509 if (this->functions_
.empty())
1512 return this->functions_
.back().blocks
.back();
1515 // Look up a name in the current binding contour. If PFUNCTION is not
1516 // NULL, set it to the function in which the name is defined, or NULL
1517 // if the name is defined in global scope.
1520 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1522 if (pfunction
!= NULL
)
1525 if (Gogo::is_sink_name(name
))
1526 return Named_object::make_sink();
1528 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1529 p
!= this->functions_
.rend();
1532 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1535 if (pfunction
!= NULL
)
1536 *pfunction
= p
->function
;
1541 if (this->package_
!= NULL
)
1543 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1546 if (ret
->package() != NULL
)
1547 ret
->package()->note_usage();
1552 // We do not look in the global namespace. If we did, the global
1553 // namespace would effectively hide names which were defined in
1554 // package scope which we have not yet seen. Instead,
1555 // define_global_names is called after parsing is over to connect
1556 // undefined names at package scope with names defined at global
1562 // Look up a name in the current block, without searching enclosing
1566 Gogo::lookup_in_block(const std::string
& name
) const
1568 go_assert(!this->functions_
.empty());
1569 go_assert(!this->functions_
.back().blocks
.empty());
1570 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1573 // Look up a name in the global namespace.
1576 Gogo::lookup_global(const char* name
) const
1578 return this->globals_
->lookup(name
);
1581 // Add an imported package.
1584 Gogo::add_imported_package(const std::string
& real_name
,
1585 const std::string
& alias_arg
,
1586 bool is_alias_exported
,
1587 const std::string
& pkgpath
,
1588 const std::string
& pkgpath_symbol
,
1590 bool* padd_to_globals
)
1592 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1593 ret
->set_package_name(real_name
, location
);
1595 *padd_to_globals
= false;
1597 if (alias_arg
== ".")
1598 *padd_to_globals
= true;
1599 else if (alias_arg
== "_")
1600 ret
->set_uses_sink_alias();
1603 std::string alias
= alias_arg
;
1607 is_alias_exported
= Lex::is_exported_name(alias
);
1609 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1610 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1611 if (!no
->is_package())
1618 // Register a package. This package may or may not be imported. This
1619 // returns the Package structure for the package, creating if it
1620 // necessary. LOCATION is the location of the import statement that
1621 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1622 // for names in the package; it may be the empty string, in which case
1623 // we either get it later or make a guess when we need it.
1626 Gogo::register_package(const std::string
& pkgpath
,
1627 const std::string
& pkgpath_symbol
, Location location
)
1629 Package
* package
= NULL
;
1630 std::pair
<Packages::iterator
, bool> ins
=
1631 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1634 // We have seen this package name before.
1635 package
= ins
.first
->second
;
1636 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1637 if (!pkgpath_symbol
.empty())
1638 package
->set_pkgpath_symbol(pkgpath_symbol
);
1639 if (Linemap::is_unknown_location(package
->location()))
1640 package
->set_location(location
);
1644 // First time we have seen this package name.
1645 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1646 go_assert(ins
.first
->second
== NULL
);
1647 ins
.first
->second
= package
;
1653 // Start compiling a function.
1656 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1657 bool add_method_to_type
, Location location
)
1659 bool at_top_level
= this->functions_
.empty();
1661 Block
* block
= new Block(NULL
, location
);
1663 Named_object
* enclosing
= (at_top_level
1665 : this->functions_
.back().function
);
1667 Function
* function
= new Function(type
, enclosing
, block
, location
);
1669 if (type
->is_method())
1671 const Typed_identifier
* receiver
= type
->receiver();
1672 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1673 true, true, location
);
1674 std::string rname
= receiver
->name();
1675 if (rname
.empty() || Gogo::is_sink_name(rname
))
1677 // We need to give receivers a name since they wind up in
1678 // DECL_ARGUMENTS. FIXME.
1679 static unsigned int count
;
1681 snprintf(buf
, sizeof buf
, "r.%u", count
);
1685 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1688 const Typed_identifier_list
* parameters
= type
->parameters();
1689 bool is_varargs
= type
->is_varargs();
1690 if (parameters
!= NULL
)
1692 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1693 p
!= parameters
->end();
1696 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1698 if (is_varargs
&& p
+ 1 == parameters
->end())
1699 param
->set_is_varargs_parameter();
1701 std::string pname
= p
->name();
1702 if (pname
.empty() || Gogo::is_sink_name(pname
))
1704 // We need to give parameters a name since they wind up
1705 // in DECL_ARGUMENTS. FIXME.
1706 static unsigned int count
;
1708 snprintf(buf
, sizeof buf
, "p.%u", count
);
1712 block
->bindings()->add_variable(pname
, NULL
, param
);
1716 function
->create_result_variables(this);
1718 const std::string
* pname
;
1719 std::string nested_name
;
1720 bool is_init
= false;
1721 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
1723 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
1724 || (type
->results() != NULL
&& !type
->results()->empty()))
1726 "func init must have no arguments and no return values");
1727 // There can be multiple "init" functions, so give them each a
1729 static int init_count
;
1731 snprintf(buf
, sizeof buf
, ".$init%d", init_count
);
1734 pname
= &nested_name
;
1737 else if (!name
.empty())
1741 // Invent a name for a nested function.
1742 static int nested_count
;
1744 snprintf(buf
, sizeof buf
, ".$nested%d", nested_count
);
1747 pname
= &nested_name
;
1751 if (Gogo::is_sink_name(*pname
))
1753 static int sink_count
;
1755 snprintf(buf
, sizeof buf
, ".$sink%d", sink_count
);
1757 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1758 ret
->func_value()->set_is_sink();
1760 else if (!type
->is_method())
1762 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
1763 if (!ret
->is_function() || ret
->func_value() != function
)
1765 // Redefinition error. Invent a name to avoid knockon
1767 static int redefinition_count
;
1769 snprintf(buf
, sizeof buf
, ".$redefined%d", redefinition_count
);
1770 ++redefinition_count
;
1771 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1776 if (!add_method_to_type
)
1777 ret
= Named_object::make_function(name
, NULL
, function
);
1780 go_assert(at_top_level
);
1781 Type
* rtype
= type
->receiver()->type();
1783 // We want to look through the pointer created by the
1784 // parser, without getting an error if the type is not yet
1786 if (rtype
->classification() == Type::TYPE_POINTER
)
1787 rtype
= rtype
->points_to();
1789 if (rtype
->is_error_type())
1790 ret
= Named_object::make_function(name
, NULL
, function
);
1791 else if (rtype
->named_type() != NULL
)
1793 ret
= rtype
->named_type()->add_method(name
, function
);
1794 if (!ret
->is_function())
1796 // Redefinition error.
1797 ret
= Named_object::make_function(name
, NULL
, function
);
1800 else if (rtype
->forward_declaration_type() != NULL
)
1802 Named_object
* type_no
=
1803 rtype
->forward_declaration_type()->named_object();
1804 if (type_no
->is_unknown())
1806 // If we are seeing methods it really must be a
1807 // type. Declare it as such. An alternative would
1808 // be to support lists of methods for unknown
1809 // expressions. Either way the error messages if
1810 // this is not a type are going to get confusing.
1811 Named_object
* declared
=
1812 this->declare_package_type(type_no
->name(),
1813 type_no
->location());
1815 == type_no
->unknown_value()->real_named_object());
1817 ret
= rtype
->forward_declaration_type()->add_method(name
,
1823 this->package_
->bindings()->add_method(ret
);
1826 this->functions_
.resize(this->functions_
.size() + 1);
1827 Open_function
& of(this->functions_
.back());
1829 of
.blocks
.push_back(block
);
1833 this->init_functions_
.push_back(ret
);
1834 this->need_init_fn_
= true;
1840 // Finish compiling a function.
1843 Gogo::finish_function(Location location
)
1845 this->finish_block(location
);
1846 go_assert(this->functions_
.back().blocks
.empty());
1847 this->functions_
.pop_back();
1850 // Return the current function.
1853 Gogo::current_function() const
1855 go_assert(!this->functions_
.empty());
1856 return this->functions_
.back().function
;
1859 // Start a new block.
1862 Gogo::start_block(Location location
)
1864 go_assert(!this->functions_
.empty());
1865 Block
* block
= new Block(this->current_block(), location
);
1866 this->functions_
.back().blocks
.push_back(block
);
1872 Gogo::finish_block(Location location
)
1874 go_assert(!this->functions_
.empty());
1875 go_assert(!this->functions_
.back().blocks
.empty());
1876 Block
* block
= this->functions_
.back().blocks
.back();
1877 this->functions_
.back().blocks
.pop_back();
1878 block
->set_end_location(location
);
1882 // Add an erroneous name.
1885 Gogo::add_erroneous_name(const std::string
& name
)
1887 return this->package_
->bindings()->add_erroneous_name(name
);
1890 // Add an unknown name.
1893 Gogo::add_unknown_name(const std::string
& name
, Location location
)
1895 return this->package_
->bindings()->add_unknown_name(name
, location
);
1898 // Declare a function.
1901 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
1904 if (!type
->is_method())
1905 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
1909 // We don't bother to add this to the list of global
1911 Type
* rtype
= type
->receiver()->type();
1913 // We want to look through the pointer created by the
1914 // parser, without getting an error if the type is not yet
1916 if (rtype
->classification() == Type::TYPE_POINTER
)
1917 rtype
= rtype
->points_to();
1919 if (rtype
->is_error_type())
1921 else if (rtype
->named_type() != NULL
)
1922 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
1924 else if (rtype
->forward_declaration_type() != NULL
)
1926 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
1927 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
1934 // Add a label definition.
1937 Gogo::add_label_definition(const std::string
& label_name
,
1940 go_assert(!this->functions_
.empty());
1941 Function
* func
= this->functions_
.back().function
->func_value();
1942 Label
* label
= func
->add_label_definition(this, label_name
, location
);
1943 this->add_statement(Statement::make_label_statement(label
, location
));
1947 // Add a label reference.
1950 Gogo::add_label_reference(const std::string
& label_name
,
1951 Location location
, bool issue_goto_errors
)
1953 go_assert(!this->functions_
.empty());
1954 Function
* func
= this->functions_
.back().function
->func_value();
1955 return func
->add_label_reference(this, label_name
, location
,
1959 // Add a function to the call graph.
1962 Gogo::add_call_node(Named_object
* function
)
1964 Node
* call
= this->lookup_call_node(function
);
1967 call
= Node::make_call(function
);
1968 this->call_graph_
.insert(call
);
1969 this->named_call_nodes_
[function
] = call
;
1974 // Find the call node that represents FUNCTION. Return NULL if it does not
1978 Gogo::lookup_call_node(Named_object
* function
) const
1980 Named_escape_nodes::const_iterator p
= this->named_call_nodes_
.find(function
);
1981 if (p
== this->named_call_nodes_
.end())
1986 // Add a connection node for OBJECT.
1989 Gogo::add_connection_node(Named_object
* object
)
1991 Node
* connection
= this->lookup_connection_node(object
);
1992 if (connection
== NULL
)
1994 connection
= Node::make_connection(object
, Node::ESCAPE_NONE
);
1996 // Each global variable is a part of the global connection graph.
1997 if (object
->is_variable()
1998 && object
->var_value()->is_global())
2000 connection
->connection_node()->set_escape_state(Node::ESCAPE_GLOBAL
);
2001 this->global_connections_
.insert(connection
);
2004 // Each function declaration or definition is the root of its own
2005 // connection graph. This means closures will have their own
2006 // connection graph that objects in the enclosing function might
2008 if (object
->is_function() || object
->is_function_declaration())
2009 this->connection_roots_
.insert(connection
);
2010 this->named_connection_nodes_
[object
] = connection
;
2015 // Find the connection node for OBJECT. Return NULL if it does not exist.
2018 Gogo::lookup_connection_node(Named_object
* object
) const
2020 Named_escape_nodes::const_iterator p
=
2021 this->named_connection_nodes_
.find(object
);
2022 if (p
== this->named_connection_nodes_
.end())
2027 // Return the current binding state.
2030 Gogo::bindings_snapshot(Location location
)
2032 return new Bindings_snapshot(this->current_block(), location
);
2038 Gogo::add_statement(Statement
* statement
)
2040 go_assert(!this->functions_
.empty()
2041 && !this->functions_
.back().blocks
.empty());
2042 this->functions_
.back().blocks
.back()->add_statement(statement
);
2048 Gogo::add_block(Block
* block
, Location location
)
2050 go_assert(!this->functions_
.empty()
2051 && !this->functions_
.back().blocks
.empty());
2052 Statement
* statement
= Statement::make_block_statement(block
, location
);
2053 this->functions_
.back().blocks
.back()->add_statement(statement
);
2059 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2062 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2068 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2070 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2072 if (!this->in_global_scope() && no
->is_type())
2074 Named_object
* f
= this->functions_
.back().function
;
2076 if (f
->is_function())
2077 index
= f
->func_value()->new_local_type_index();
2080 no
->type_value()->set_in_function(f
, index
);
2084 // Add a named type.
2087 Gogo::add_named_type(Named_type
* type
)
2089 go_assert(this->in_global_scope());
2090 this->current_bindings()->add_named_type(type
);
2096 Gogo::declare_type(const std::string
& name
, Location location
)
2098 Bindings
* bindings
= this->current_bindings();
2099 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2100 if (!this->in_global_scope() && no
->is_type_declaration())
2102 Named_object
* f
= this->functions_
.back().function
;
2104 if (f
->is_function())
2105 index
= f
->func_value()->new_local_type_index();
2108 no
->type_declaration_value()->set_in_function(f
, index
);
2113 // Declare a type at the package level.
2116 Gogo::declare_package_type(const std::string
& name
, Location location
)
2118 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2121 // Declare a function at the package level.
2124 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2127 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2131 // Define a type which was already declared.
2134 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2136 this->current_bindings()->define_type(no
, type
);
2142 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2144 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2147 // In a function the middle-end wants to see a DECL_EXPR node.
2149 && no
->is_variable()
2150 && !no
->var_value()->is_parameter()
2151 && !this->functions_
.empty())
2152 this->add_statement(Statement::make_variable_declaration(no
));
2157 // Add a sink--a reference to the blank identifier _.
2162 return Named_object::make_sink();
2165 // Add a named object for a dot import.
2168 Gogo::add_dot_import_object(Named_object
* no
)
2170 // If the name already exists, then it was defined in some file seen
2171 // earlier. If the earlier name is just a declaration, don't add
2172 // this name, because that will cause the previous declaration to
2173 // merge to this imported name, which should not happen. Just add
2174 // this name to the list of file block names to get appropriate
2175 // errors if we see a later definition.
2176 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2177 if (e
!= NULL
&& e
->package() == NULL
)
2179 if (e
->is_unknown())
2181 if (e
->package() == NULL
2182 && (e
->is_type_declaration()
2183 || e
->is_function_declaration()
2184 || e
->is_unknown()))
2186 this->add_file_block_name(no
->name(), no
->location());
2191 this->current_bindings()->add_named_object(no
);
2194 // Mark all local variables used. This is used when some types of
2195 // parse error occur.
2198 Gogo::mark_locals_used()
2200 for (Open_functions::iterator pf
= this->functions_
.begin();
2201 pf
!= this->functions_
.end();
2204 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2205 pb
!= pf
->blocks
.end();
2207 (*pb
)->bindings()->mark_locals_used();
2211 // Record that we've seen an interface type.
2214 Gogo::record_interface_type(Interface_type
* itype
)
2216 this->interface_types_
.push_back(itype
);
2219 // Return an erroneous name that indicates that an error has already
2223 Gogo::erroneous_name()
2225 static int erroneous_count
;
2227 snprintf(name
, sizeof name
, "$erroneous%d", erroneous_count
);
2232 // Return whether a name is an erroneous name.
2235 Gogo::is_erroneous_name(const std::string
& name
)
2237 return name
.compare(0, 10, "$erroneous") == 0;
2240 // Return a name for a thunk object.
2245 static int thunk_count
;
2246 char thunk_name
[50];
2247 snprintf(thunk_name
, sizeof thunk_name
, "$thunk%d", thunk_count
);
2252 // Return whether a function is a thunk.
2255 Gogo::is_thunk(const Named_object
* no
)
2257 return no
->name().compare(0, 6, "$thunk") == 0;
2260 // Define the global names. We do this only after parsing all the
2261 // input files, because the program might define the global names
2265 Gogo::define_global_names()
2267 for (Bindings::const_declarations_iterator p
=
2268 this->globals_
->begin_declarations();
2269 p
!= this->globals_
->end_declarations();
2272 Named_object
* global_no
= p
->second
;
2273 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2274 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2278 if (no
->is_type_declaration())
2280 if (global_no
->is_type())
2282 if (no
->type_declaration_value()->has_methods())
2283 error_at(no
->location(),
2284 "may not define methods for global type");
2285 no
->set_type_value(global_no
->type_value());
2289 error_at(no
->location(), "expected type");
2290 Type
* errtype
= Type::make_error_type();
2292 Named_object::make_type("erroneous_type", NULL
, errtype
,
2293 Linemap::predeclared_location());
2294 no
->set_type_value(err
->type_value());
2297 else if (no
->is_unknown())
2298 no
->unknown_value()->set_real_named_object(global_no
);
2301 // Give an error if any name is defined in both the package block
2302 // and the file block. For example, this can happen if one file
2303 // imports "fmt" and another file defines a global variable fmt.
2304 for (Bindings::const_declarations_iterator p
=
2305 this->package_
->bindings()->begin_declarations();
2306 p
!= this->package_
->bindings()->end_declarations();
2309 if (p
->second
->is_unknown()
2310 && p
->second
->unknown_value()->real_named_object() == NULL
)
2312 // No point in warning about an undefined name, as we will
2313 // get other errors later anyhow.
2316 File_block_names::const_iterator pf
=
2317 this->file_block_names_
.find(p
->second
->name());
2318 if (pf
!= this->file_block_names_
.end())
2320 std::string n
= p
->second
->message_name();
2321 error_at(p
->second
->location(),
2322 "%qs defined as both imported name and global name",
2324 inform(pf
->second
, "%qs imported here", n
.c_str());
2327 // No package scope identifier may be named "init".
2328 if (!p
->second
->is_function()
2329 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2331 error_at(p
->second
->location(),
2332 "cannot declare init - must be func");
2337 // Clear out names in file scope.
2340 Gogo::clear_file_scope()
2342 this->package_
->bindings()->clear_file_scope(this);
2344 // Warn about packages which were imported but not used.
2345 bool quiet
= saw_errors();
2346 for (Packages::iterator p
= this->packages_
.begin();
2347 p
!= this->packages_
.end();
2350 Package
* package
= p
->second
;
2351 if (package
!= this->package_
2352 && package
->is_imported()
2354 && !package
->uses_sink_alias()
2356 error_at(package
->location(), "imported and not used: %s",
2357 Gogo::message_name(package
->package_name()).c_str());
2358 package
->clear_is_imported();
2359 package
->clear_uses_sink_alias();
2360 package
->clear_used();
2364 // Queue up a type specific function for later writing. These are
2365 // written out in write_specific_type_functions, called after the
2366 // parse tree is lowered.
2369 Gogo::queue_specific_type_function(Type
* type
, Named_type
* name
,
2370 const std::string
& hash_name
,
2371 Function_type
* hash_fntype
,
2372 const std::string
& equal_name
,
2373 Function_type
* equal_fntype
)
2375 go_assert(!this->specific_type_functions_are_written_
);
2376 go_assert(!this->in_global_scope());
2377 Specific_type_function
* tsf
= new Specific_type_function(type
, name
,
2382 this->specific_type_functions_
.push_back(tsf
);
2385 // Look for types which need specific hash or equality functions.
2387 class Specific_type_functions
: public Traverse
2390 Specific_type_functions(Gogo
* gogo
)
2391 : Traverse(traverse_types
),
2403 Specific_type_functions::type(Type
* t
)
2405 Named_object
* hash_fn
;
2406 Named_object
* equal_fn
;
2407 switch (t
->classification())
2409 case Type::TYPE_NAMED
:
2411 Named_type
* nt
= t
->named_type();
2412 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2413 t
->type_functions(this->gogo_
, nt
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2415 // If this is a struct type, we don't want to make functions
2416 // for the unnamed struct.
2417 Type
* rt
= nt
->real_type();
2418 if (rt
->struct_type() == NULL
)
2420 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2421 return TRAVERSE_EXIT
;
2425 // If this type is defined in another package, then we don't
2426 // need to worry about the unexported fields.
2427 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2428 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2429 for (Struct_field_list::const_iterator p
= fields
->begin();
2433 if (is_defined_elsewhere
2434 && Gogo::is_hidden_name(p
->field_name()))
2436 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2437 return TRAVERSE_EXIT
;
2441 return TRAVERSE_SKIP_COMPONENTS
;
2444 case Type::TYPE_STRUCT
:
2445 case Type::TYPE_ARRAY
:
2446 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2447 t
->type_functions(this->gogo_
, NULL
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2454 return TRAVERSE_CONTINUE
;
2457 // Write out type specific functions.
2460 Gogo::write_specific_type_functions()
2462 Specific_type_functions
stf(this);
2463 this->traverse(&stf
);
2465 while (!this->specific_type_functions_
.empty())
2467 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2468 this->specific_type_functions_
.pop_back();
2469 tsf
->type
->write_specific_type_functions(this, tsf
->name
,
2476 this->specific_type_functions_are_written_
= true;
2479 // Traverse the tree.
2482 Gogo::traverse(Traverse
* traverse
)
2484 // Traverse the current package first for consistency. The other
2485 // packages will only contain imported types, constants, and
2487 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2489 for (Packages::const_iterator p
= this->packages_
.begin();
2490 p
!= this->packages_
.end();
2493 if (p
->second
!= this->package_
)
2495 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2501 // Add a type to verify. This is used for types of sink variables, in
2502 // order to give appropriate error messages.
2505 Gogo::add_type_to_verify(Type
* type
)
2507 this->verify_types_
.push_back(type
);
2510 // Traversal class used to verify types.
2512 class Verify_types
: public Traverse
2516 : Traverse(traverse_types
)
2523 // Verify that a type is correct.
2526 Verify_types::type(Type
* t
)
2529 return TRAVERSE_SKIP_COMPONENTS
;
2530 return TRAVERSE_CONTINUE
;
2533 // Verify that all types are correct.
2536 Gogo::verify_types()
2538 Verify_types traverse
;
2539 this->traverse(&traverse
);
2541 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2542 p
!= this->verify_types_
.end();
2545 this->verify_types_
.clear();
2548 // Traversal class used to lower parse tree.
2550 class Lower_parse_tree
: public Traverse
2553 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2554 : Traverse(traverse_variables
2555 | traverse_constants
2556 | traverse_functions
2557 | traverse_statements
2558 | traverse_expressions
),
2559 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2563 set_inserter(const Statement_inserter
* inserter
)
2564 { this->inserter_
= *inserter
; }
2567 variable(Named_object
*);
2570 constant(Named_object
*, bool);
2573 function(Named_object
*);
2576 statement(Block
*, size_t* pindex
, Statement
*);
2579 expression(Expression
**);
2584 // The function we are traversing.
2585 Named_object
* function_
;
2586 // Value to use for the predeclared constant iota.
2588 // Current statement inserter for use by expressions.
2589 Statement_inserter inserter_
;
2595 Lower_parse_tree::variable(Named_object
* no
)
2597 if (!no
->is_variable())
2598 return TRAVERSE_CONTINUE
;
2600 if (no
->is_variable() && no
->var_value()->is_global())
2602 // Global variables can have loops in their initialization
2603 // expressions. This is handled in lower_init_expression.
2604 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2606 return TRAVERSE_CONTINUE
;
2609 // This is a local variable. We are going to return
2610 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2611 // initialization expression when we reach the variable declaration
2612 // statement. However, that means that we need to traverse the type
2614 if (no
->var_value()->has_type())
2616 Type
* type
= no
->var_value()->type();
2619 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2620 return TRAVERSE_EXIT
;
2623 go_assert(!no
->var_value()->has_pre_init());
2625 return TRAVERSE_SKIP_COMPONENTS
;
2628 // Lower constants. We handle constants specially so that we can set
2629 // the right value for the predeclared constant iota. This works in
2630 // conjunction with the way we lower Const_expression objects.
2633 Lower_parse_tree::constant(Named_object
* no
, bool)
2635 Named_constant
* nc
= no
->const_value();
2637 // Don't get into trouble if the constant's initializer expression
2638 // refers to the constant itself.
2640 return TRAVERSE_CONTINUE
;
2643 go_assert(this->iota_value_
== -1);
2644 this->iota_value_
= nc
->iota_value();
2645 nc
->traverse_expression(this);
2646 this->iota_value_
= -1;
2648 nc
->clear_lowering();
2650 // We will traverse the expression a second time, but that will be
2653 return TRAVERSE_CONTINUE
;
2656 // Lower the body of a function, and set the closure type. Record the
2657 // function while lowering it, so that we can pass it down when
2658 // lowering an expression.
2661 Lower_parse_tree::function(Named_object
* no
)
2663 no
->func_value()->set_closure_type();
2665 go_assert(this->function_
== NULL
);
2666 this->function_
= no
;
2667 int t
= no
->func_value()->traverse(this);
2668 this->function_
= NULL
;
2670 if (t
== TRAVERSE_EXIT
)
2672 return TRAVERSE_SKIP_COMPONENTS
;
2675 // Lower statement parse trees.
2678 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
2680 // Because we explicitly traverse the statement's contents
2681 // ourselves, we want to skip block statements here. There is
2682 // nothing to lower in a block statement.
2683 if (sorig
->is_block_statement())
2684 return TRAVERSE_CONTINUE
;
2686 Statement_inserter
hold_inserter(this->inserter_
);
2687 this->inserter_
= Statement_inserter(block
, pindex
);
2689 // Lower the expressions first.
2690 int t
= sorig
->traverse_contents(this);
2691 if (t
== TRAVERSE_EXIT
)
2693 this->inserter_
= hold_inserter
;
2697 // Keep lowering until nothing changes.
2698 Statement
* s
= sorig
;
2701 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
2706 t
= s
->traverse_contents(this);
2707 if (t
== TRAVERSE_EXIT
)
2709 this->inserter_
= hold_inserter
;
2715 block
->replace_statement(*pindex
, s
);
2717 this->inserter_
= hold_inserter
;
2718 return TRAVERSE_SKIP_COMPONENTS
;
2721 // Lower expression parse trees.
2724 Lower_parse_tree::expression(Expression
** pexpr
)
2726 // We have to lower all subexpressions first, so that we can get
2727 // their type if necessary. This is awkward, because we don't have
2728 // a postorder traversal pass.
2729 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2730 return TRAVERSE_EXIT
;
2731 // Keep lowering until nothing changes.
2734 Expression
* e
= *pexpr
;
2735 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
2736 &this->inserter_
, this->iota_value_
);
2739 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2740 return TRAVERSE_EXIT
;
2743 return TRAVERSE_SKIP_COMPONENTS
;
2746 // Lower the parse tree. This is called after the parse is complete,
2747 // when all names should be resolved.
2750 Gogo::lower_parse_tree()
2752 Lower_parse_tree
lower_parse_tree(this, NULL
);
2753 this->traverse(&lower_parse_tree
);
2759 Gogo::lower_block(Named_object
* function
, Block
* block
)
2761 Lower_parse_tree
lower_parse_tree(this, function
);
2762 block
->traverse(&lower_parse_tree
);
2765 // Lower an expression. INSERTER may be NULL, in which case the
2766 // expression had better not need to create any temporaries.
2769 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
2772 Lower_parse_tree
lower_parse_tree(this, function
);
2773 if (inserter
!= NULL
)
2774 lower_parse_tree
.set_inserter(inserter
);
2775 lower_parse_tree
.expression(pexpr
);
2778 // Lower a constant. This is called when lowering a reference to a
2779 // constant. We have to make sure that the constant has already been
2783 Gogo::lower_constant(Named_object
* no
)
2785 go_assert(no
->is_const());
2786 Lower_parse_tree
lower(this, NULL
);
2787 lower
.constant(no
, false);
2790 // Traverse the tree to create function descriptors as needed.
2792 class Create_function_descriptors
: public Traverse
2795 Create_function_descriptors(Gogo
* gogo
)
2796 : Traverse(traverse_functions
| traverse_expressions
),
2801 function(Named_object
*);
2804 expression(Expression
**);
2810 // Create a descriptor for every top-level exported function.
2813 Create_function_descriptors::function(Named_object
* no
)
2815 if (no
->is_function()
2816 && no
->func_value()->enclosing() == NULL
2817 && !no
->func_value()->is_method()
2818 && !Gogo::is_hidden_name(no
->name())
2819 && !Gogo::is_thunk(no
))
2820 no
->func_value()->descriptor(this->gogo_
, no
);
2822 return TRAVERSE_CONTINUE
;
2825 // If we see a function referenced in any way other than calling it,
2826 // create a descriptor for it.
2829 Create_function_descriptors::expression(Expression
** pexpr
)
2831 Expression
* expr
= *pexpr
;
2833 Func_expression
* fe
= expr
->func_expression();
2836 // We would not get here for a call to this function, so this is
2837 // a reference to a function other than calling it. We need a
2839 if (fe
->closure() != NULL
)
2840 return TRAVERSE_CONTINUE
;
2841 Named_object
* no
= fe
->named_object();
2842 if (no
->is_function() && !no
->func_value()->is_method())
2843 no
->func_value()->descriptor(this->gogo_
, no
);
2844 else if (no
->is_function_declaration()
2845 && !no
->func_declaration_value()->type()->is_method()
2846 && !Linemap::is_predeclared_location(no
->location()))
2847 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
2848 return TRAVERSE_CONTINUE
;
2851 Bound_method_expression
* bme
= expr
->bound_method_expression();
2854 // We would not get here for a call to this method, so this is a
2855 // method value. We need to create a thunk.
2856 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
2858 return TRAVERSE_CONTINUE
;
2861 Interface_field_reference_expression
* ifre
=
2862 expr
->interface_field_reference_expression();
2865 // We would not get here for a call to this interface method, so
2866 // this is a method value. We need to create a thunk.
2867 Interface_type
* type
= ifre
->expr()->type()->interface_type();
2869 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
2871 return TRAVERSE_CONTINUE
;
2874 Call_expression
* ce
= expr
->call_expression();
2877 Expression
* fn
= ce
->fn();
2878 if (fn
->func_expression() != NULL
2879 || fn
->bound_method_expression() != NULL
2880 || fn
->interface_field_reference_expression() != NULL
)
2882 // Traverse the arguments but not the function.
2883 Expression_list
* args
= ce
->args();
2886 if (args
->traverse(this) == TRAVERSE_EXIT
)
2887 return TRAVERSE_EXIT
;
2889 return TRAVERSE_SKIP_COMPONENTS
;
2893 return TRAVERSE_CONTINUE
;
2896 // Create function descriptors as needed. We need a function
2897 // descriptor for all exported functions and for all functions that
2898 // are referenced without being called.
2901 Gogo::create_function_descriptors()
2903 // Create a function descriptor for any exported function that is
2904 // declared in this package. This is so that we have a descriptor
2905 // for functions written in assembly. Gather the descriptors first
2906 // so that we don't add declarations while looping over them.
2907 std::vector
<Named_object
*> fndecls
;
2908 Bindings
* b
= this->package_
->bindings();
2909 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
2910 p
!= b
->end_declarations();
2913 Named_object
* no
= p
->second
;
2914 if (no
->is_function_declaration()
2915 && !no
->func_declaration_value()->type()->is_method()
2916 && !Linemap::is_predeclared_location(no
->location())
2917 && !Gogo::is_hidden_name(no
->name()))
2918 fndecls
.push_back(no
);
2920 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
2923 (*p
)->func_declaration_value()->descriptor(this, *p
);
2926 Create_function_descriptors
cfd(this);
2927 this->traverse(&cfd
);
2930 // Look for interface types to finalize methods of inherited
2933 class Finalize_methods
: public Traverse
2936 Finalize_methods(Gogo
* gogo
)
2937 : Traverse(traverse_types
),
2948 // Finalize the methods of an interface type.
2951 Finalize_methods::type(Type
* t
)
2953 // Check the classification so that we don't finalize the methods
2954 // twice for a named interface type.
2955 switch (t
->classification())
2957 case Type::TYPE_INTERFACE
:
2958 t
->interface_type()->finalize_methods();
2961 case Type::TYPE_NAMED
:
2963 // We have to finalize the methods of the real type first.
2964 // But if the real type is a struct type, then we only want to
2965 // finalize the methods of the field types, not of the struct
2966 // type itself. We don't want to add methods to the struct,
2967 // since it has a name.
2968 Named_type
* nt
= t
->named_type();
2969 Type
* rt
= nt
->real_type();
2970 if (rt
->classification() != Type::TYPE_STRUCT
)
2972 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2973 return TRAVERSE_EXIT
;
2977 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
2978 return TRAVERSE_EXIT
;
2981 nt
->finalize_methods(this->gogo_
);
2983 // If this type is defined in a different package, then finalize the
2984 // types of all the methods, since we won't see them otherwise.
2985 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
2987 const Methods
* methods
= nt
->methods();
2988 for (Methods::const_iterator p
= methods
->begin();
2989 p
!= methods
->end();
2992 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
2993 return TRAVERSE_EXIT
;
2997 // Finalize the types of all methods that are declared but not
2998 // defined, since we won't see the declarations otherwise.
2999 if (nt
->named_object()->package() == NULL
3000 && nt
->local_methods() != NULL
)
3002 const Bindings
* methods
= nt
->local_methods();
3003 for (Bindings::const_declarations_iterator p
=
3004 methods
->begin_declarations();
3005 p
!= methods
->end_declarations();
3008 if (p
->second
->is_function_declaration())
3010 Type
* mt
= p
->second
->func_declaration_value()->type();
3011 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3012 return TRAVERSE_EXIT
;
3017 return TRAVERSE_SKIP_COMPONENTS
;
3020 case Type::TYPE_STRUCT
:
3021 // Traverse the field types first in case there is an embedded
3022 // field with methods that the struct should inherit.
3023 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3024 return TRAVERSE_EXIT
;
3025 t
->struct_type()->finalize_methods(this->gogo_
);
3026 return TRAVERSE_SKIP_COMPONENTS
;
3032 return TRAVERSE_CONTINUE
;
3035 // Finalize method lists and build stub methods for types.
3038 Gogo::finalize_methods()
3040 Finalize_methods
finalize(this);
3041 this->traverse(&finalize
);
3044 // Set types for unspecified variables and constants.
3047 Gogo::determine_types()
3049 Bindings
* bindings
= this->current_bindings();
3050 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3051 p
!= bindings
->end_definitions();
3054 if ((*p
)->is_function())
3055 (*p
)->func_value()->determine_types();
3056 else if ((*p
)->is_variable())
3057 (*p
)->var_value()->determine_type();
3058 else if ((*p
)->is_const())
3059 (*p
)->const_value()->determine_type();
3061 // See if a variable requires us to build an initialization
3062 // function. We know that we will see all global variables
3064 if (!this->need_init_fn_
&& (*p
)->is_variable())
3066 Variable
* variable
= (*p
)->var_value();
3068 // If this is a global variable which requires runtime
3069 // initialization, we need an initialization function.
3070 if (!variable
->is_global())
3072 else if (variable
->init() == NULL
)
3074 else if (variable
->type()->interface_type() != NULL
)
3075 this->need_init_fn_
= true;
3076 else if (variable
->init()->is_constant())
3078 else if (!variable
->init()->is_composite_literal())
3079 this->need_init_fn_
= true;
3080 else if (variable
->init()->is_nonconstant_composite_literal())
3081 this->need_init_fn_
= true;
3083 // If this is a global variable which holds a pointer value,
3084 // then we need an initialization function to register it as a
3086 if (variable
->is_global() && variable
->type()->has_pointer())
3087 this->need_init_fn_
= true;
3091 // Determine the types of constants in packages.
3092 for (Packages::const_iterator p
= this->packages_
.begin();
3093 p
!= this->packages_
.end();
3095 p
->second
->determine_types();
3098 // Traversal class used for type checking.
3100 class Check_types_traverse
: public Traverse
3103 Check_types_traverse(Gogo
* gogo
)
3104 : Traverse(traverse_variables
3105 | traverse_constants
3106 | traverse_functions
3107 | traverse_statements
3108 | traverse_expressions
),
3113 variable(Named_object
*);
3116 constant(Named_object
*, bool);
3119 function(Named_object
*);
3122 statement(Block
*, size_t* pindex
, Statement
*);
3125 expression(Expression
**);
3132 // Check that a variable initializer has the right type.
3135 Check_types_traverse::variable(Named_object
* named_object
)
3137 if (named_object
->is_variable())
3139 Variable
* var
= named_object
->var_value();
3141 // Give error if variable type is not defined.
3142 var
->type()->base();
3144 Expression
* init
= var
->init();
3147 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3150 error_at(var
->location(), "incompatible type in initialization");
3152 error_at(var
->location(),
3153 "incompatible type in initialization (%s)",
3157 else if (init
!= NULL
3158 && init
->func_expression() != NULL
)
3160 Named_object
* no
= init
->func_expression()->named_object();
3161 Function_type
* fntype
;
3162 if (no
->is_function())
3163 fntype
= no
->func_value()->type();
3164 else if (no
->is_function_declaration())
3165 fntype
= no
->func_declaration_value()->type();
3169 // Builtin functions cannot be used as function values for variable
3171 if (fntype
->is_builtin())
3173 error_at(init
->location(),
3174 "invalid use of special builtin function %qs; "
3176 no
->message_name().c_str());
3179 else if (!var
->is_used()
3180 && !var
->is_global()
3181 && !var
->is_parameter()
3182 && !var
->is_receiver()
3183 && !var
->type()->is_error()
3184 && (init
== NULL
|| !init
->is_error_expression())
3185 && !Lex::is_invalid_identifier(named_object
->name()))
3186 error_at(var
->location(), "%qs declared and not used",
3187 named_object
->message_name().c_str());
3189 return TRAVERSE_CONTINUE
;
3192 // Check that a constant initializer has the right type.
3195 Check_types_traverse::constant(Named_object
* named_object
, bool)
3197 Named_constant
* constant
= named_object
->const_value();
3198 Type
* ctype
= constant
->type();
3199 if (ctype
->integer_type() == NULL
3200 && ctype
->float_type() == NULL
3201 && ctype
->complex_type() == NULL
3202 && !ctype
->is_boolean_type()
3203 && !ctype
->is_string_type())
3205 if (ctype
->is_nil_type())
3206 error_at(constant
->location(), "const initializer cannot be nil");
3207 else if (!ctype
->is_error())
3208 error_at(constant
->location(), "invalid constant type");
3209 constant
->set_error();
3211 else if (!constant
->expr()->is_constant())
3213 error_at(constant
->expr()->location(), "expression is not constant");
3214 constant
->set_error();
3216 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3219 error_at(constant
->location(),
3220 "initialization expression has wrong type");
3221 constant
->set_error();
3223 return TRAVERSE_CONTINUE
;
3226 // There are no types to check in a function, but this is where we
3227 // issue warnings about labels which are defined but not referenced.
3230 Check_types_traverse::function(Named_object
* no
)
3232 no
->func_value()->check_labels();
3233 return TRAVERSE_CONTINUE
;
3236 // Check that types are valid in a statement.
3239 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3241 s
->check_types(this->gogo_
);
3242 return TRAVERSE_CONTINUE
;
3245 // Check that types are valid in an expression.
3248 Check_types_traverse::expression(Expression
** expr
)
3250 (*expr
)->check_types(this->gogo_
);
3251 return TRAVERSE_CONTINUE
;
3254 // Check that types are valid.
3259 Check_types_traverse
traverse(this);
3260 this->traverse(&traverse
);
3262 Bindings
* bindings
= this->current_bindings();
3263 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3264 p
!= bindings
->end_declarations();
3267 // Also check the types in a function declaration's signature.
3268 Named_object
* no
= p
->second
;
3269 if (no
->is_function_declaration())
3270 no
->func_declaration_value()->check_types();
3274 // Check the types in a single block.
3277 Gogo::check_types_in_block(Block
* block
)
3279 Check_types_traverse
traverse(this);
3280 block
->traverse(&traverse
);
3283 // A traversal class used to find a single shortcut operator within an
3286 class Find_shortcut
: public Traverse
3290 : Traverse(traverse_blocks
3291 | traverse_statements
3292 | traverse_expressions
),
3296 // A pointer to the expression which was found, or NULL if none was
3300 { return this->found_
; }
3305 { return TRAVERSE_SKIP_COMPONENTS
; }
3308 statement(Block
*, size_t*, Statement
*)
3309 { return TRAVERSE_SKIP_COMPONENTS
; }
3312 expression(Expression
**);
3315 Expression
** found_
;
3318 // Find a shortcut expression.
3321 Find_shortcut::expression(Expression
** pexpr
)
3323 Expression
* expr
= *pexpr
;
3324 Binary_expression
* be
= expr
->binary_expression();
3326 return TRAVERSE_CONTINUE
;
3327 Operator op
= be
->op();
3328 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
3329 return TRAVERSE_CONTINUE
;
3330 go_assert(this->found_
== NULL
);
3331 this->found_
= pexpr
;
3332 return TRAVERSE_EXIT
;
3335 // A traversal class used to turn shortcut operators into explicit if
3338 class Shortcuts
: public Traverse
3341 Shortcuts(Gogo
* gogo
)
3342 : Traverse(traverse_variables
3343 | traverse_statements
),
3349 variable(Named_object
*);
3352 statement(Block
*, size_t*, Statement
*);
3355 // Convert a shortcut operator.
3357 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
3363 // Remove shortcut operators in a single statement.
3366 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3368 // FIXME: This approach doesn't work for switch statements, because
3369 // we add the new statements before the whole switch when we need to
3370 // instead add them just before the switch expression. The right
3371 // fix is probably to lower switch statements with nonconstant cases
3372 // to a series of conditionals.
3373 if (s
->switch_statement() != NULL
)
3374 return TRAVERSE_CONTINUE
;
3378 Find_shortcut find_shortcut
;
3380 // If S is a variable declaration, then ordinary traversal won't
3381 // do anything. We want to explicitly traverse the
3382 // initialization expression if there is one.
3383 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3384 Expression
* init
= NULL
;
3386 s
->traverse_contents(&find_shortcut
);
3389 init
= vds
->var()->var_value()->init();
3391 return TRAVERSE_CONTINUE
;
3392 init
->traverse(&init
, &find_shortcut
);
3394 Expression
** pshortcut
= find_shortcut
.found();
3395 if (pshortcut
== NULL
)
3396 return TRAVERSE_CONTINUE
;
3398 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
3399 block
->insert_statement_before(*pindex
, snew
);
3402 if (pshortcut
== &init
)
3403 vds
->var()->var_value()->set_init(init
);
3407 // Remove shortcut operators in the initializer of a global variable.
3410 Shortcuts::variable(Named_object
* no
)
3412 if (no
->is_result_variable())
3413 return TRAVERSE_CONTINUE
;
3414 Variable
* var
= no
->var_value();
3415 Expression
* init
= var
->init();
3416 if (!var
->is_global() || init
== NULL
)
3417 return TRAVERSE_CONTINUE
;
3421 Find_shortcut find_shortcut
;
3422 init
->traverse(&init
, &find_shortcut
);
3423 Expression
** pshortcut
= find_shortcut
.found();
3424 if (pshortcut
== NULL
)
3425 return TRAVERSE_CONTINUE
;
3427 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
3428 var
->add_preinit_statement(this->gogo_
, snew
);
3429 if (pshortcut
== &init
)
3430 var
->set_init(init
);
3434 // Given an expression which uses a shortcut operator, return a
3435 // statement which implements it, and update *PSHORTCUT accordingly.
3438 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
3440 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
3441 Expression
* left
= shortcut
->left();
3442 Expression
* right
= shortcut
->right();
3443 Location loc
= shortcut
->location();
3445 Block
* retblock
= new Block(enclosing
, loc
);
3446 retblock
->set_end_location(loc
);
3448 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
3450 retblock
->add_statement(ts
);
3452 Block
* block
= new Block(retblock
, loc
);
3453 block
->set_end_location(loc
);
3454 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
3455 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
3456 block
->add_statement(assign
);
3458 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
3459 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
3460 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
3462 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
3464 retblock
->add_statement(if_statement
);
3466 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
3470 // Now convert any shortcut operators in LEFT and RIGHT.
3471 Shortcuts
shortcuts(this->gogo_
);
3472 retblock
->traverse(&shortcuts
);
3474 return Statement::make_block_statement(retblock
, loc
);
3477 // Turn shortcut operators into explicit if statements. Doing this
3478 // considerably simplifies the order of evaluation rules.
3481 Gogo::remove_shortcuts()
3483 Shortcuts
shortcuts(this);
3484 this->traverse(&shortcuts
);
3487 // A traversal class which finds all the expressions which must be
3488 // evaluated in order within a statement or larger expression. This
3489 // is used to implement the rules about order of evaluation.
3491 class Find_eval_ordering
: public Traverse
3494 typedef std::vector
<Expression
**> Expression_pointers
;
3497 Find_eval_ordering()
3498 : Traverse(traverse_blocks
3499 | traverse_statements
3500 | traverse_expressions
),
3506 { return this->exprs_
.size(); }
3508 typedef Expression_pointers::const_iterator const_iterator
;
3512 { return this->exprs_
.begin(); }
3516 { return this->exprs_
.end(); }
3521 { return TRAVERSE_SKIP_COMPONENTS
; }
3524 statement(Block
*, size_t*, Statement
*)
3525 { return TRAVERSE_SKIP_COMPONENTS
; }
3528 expression(Expression
**);
3531 // A list of pointers to expressions with side-effects.
3532 Expression_pointers exprs_
;
3535 // If an expression must be evaluated in order, put it on the list.
3538 Find_eval_ordering::expression(Expression
** expression_pointer
)
3540 // We have to look at subexpressions before this one.
3541 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3542 return TRAVERSE_EXIT
;
3543 if ((*expression_pointer
)->must_eval_in_order())
3544 this->exprs_
.push_back(expression_pointer
);
3545 return TRAVERSE_SKIP_COMPONENTS
;
3548 // A traversal class for ordering evaluations.
3550 class Order_eval
: public Traverse
3553 Order_eval(Gogo
* gogo
)
3554 : Traverse(traverse_variables
3555 | traverse_statements
),
3560 variable(Named_object
*);
3563 statement(Block
*, size_t*, Statement
*);
3570 // Implement the order of evaluation rules for a statement.
3573 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3575 // FIXME: This approach doesn't work for switch statements, because
3576 // we add the new statements before the whole switch when we need to
3577 // instead add them just before the switch expression. The right
3578 // fix is probably to lower switch statements with nonconstant cases
3579 // to a series of conditionals.
3580 if (s
->switch_statement() != NULL
)
3581 return TRAVERSE_CONTINUE
;
3583 Find_eval_ordering find_eval_ordering
;
3585 // If S is a variable declaration, then ordinary traversal won't do
3586 // anything. We want to explicitly traverse the initialization
3587 // expression if there is one.
3588 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3589 Expression
* init
= NULL
;
3590 Expression
* orig_init
= NULL
;
3592 s
->traverse_contents(&find_eval_ordering
);
3595 init
= vds
->var()->var_value()->init();
3597 return TRAVERSE_CONTINUE
;
3600 // It might seem that this could be
3601 // init->traverse_subexpressions. Unfortunately that can fail
3604 // newvar, err := call(arg())
3605 // Here newvar will have an init of call result 0 of
3606 // call(arg()). If we only traverse subexpressions, we will
3607 // only find arg(), and we won't bother to move anything out.
3608 // Then we get to the assignment to err, we will traverse the
3609 // whole statement, and this time we will find both call() and
3610 // arg(), and so we will move them out. This will cause them to
3611 // be put into temporary variables before the assignment to err
3612 // but after the declaration of newvar. To avoid that problem,
3613 // we traverse the entire expression here.
3614 Expression::traverse(&init
, &find_eval_ordering
);
3617 size_t c
= find_eval_ordering
.size();
3619 return TRAVERSE_CONTINUE
;
3621 // If there is only one expression with a side-effect, we can
3622 // usually leave it in place.
3625 switch (s
->classification())
3627 case Statement::STATEMENT_ASSIGNMENT
:
3628 // For an assignment statement, we need to evaluate an
3629 // expression on the right hand side before we evaluate any
3630 // index expression on the left hand side, so for that case
3631 // we always move the expression. Otherwise we mishandle
3632 // m[0] = len(m) where m is a map.
3635 case Statement::STATEMENT_EXPRESSION
:
3637 // If this is a call statement that doesn't return any
3638 // values, it will not have been counted as a value to
3639 // move. We need to move any subexpressions in case they
3640 // are themselves call statements that require passing a
3642 Expression
* expr
= s
->expression_statement()->expr();
3643 if (expr
->call_expression() != NULL
3644 && expr
->call_expression()->result_count() == 0)
3646 return TRAVERSE_CONTINUE
;
3650 // We can leave the expression in place.
3651 return TRAVERSE_CONTINUE
;
3655 bool is_thunk
= s
->thunk_statement() != NULL
;
3656 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3657 p
!= find_eval_ordering
.end();
3660 Expression
** pexpr
= *p
;
3662 // The last expression in a thunk will be the call passed to go
3663 // or defer, which we must not evaluate early.
3664 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
3667 Location loc
= (*pexpr
)->location();
3669 if ((*pexpr
)->call_expression() == NULL
3670 || (*pexpr
)->call_expression()->result_count() < 2)
3672 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3675 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3679 // A call expression which returns multiple results needs to
3680 // be handled specially. We can't create a temporary
3681 // because there is no type to give it. Any actual uses of
3682 // the values will be done via Call_result_expressions.
3683 s
= Statement::make_statement(*pexpr
, true);
3686 block
->insert_statement_before(*pindex
, s
);
3690 if (init
!= orig_init
)
3691 vds
->var()->var_value()->set_init(init
);
3693 return TRAVERSE_CONTINUE
;
3696 // Implement the order of evaluation rules for the initializer of a
3700 Order_eval::variable(Named_object
* no
)
3702 if (no
->is_result_variable())
3703 return TRAVERSE_CONTINUE
;
3704 Variable
* var
= no
->var_value();
3705 Expression
* init
= var
->init();
3706 if (!var
->is_global() || init
== NULL
)
3707 return TRAVERSE_CONTINUE
;
3709 Find_eval_ordering find_eval_ordering
;
3710 Expression::traverse(&init
, &find_eval_ordering
);
3712 if (find_eval_ordering
.size() <= 1)
3714 // If there is only one expression with a side-effect, we can
3715 // leave it in place.
3716 return TRAVERSE_SKIP_COMPONENTS
;
3719 Expression
* orig_init
= init
;
3721 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3722 p
!= find_eval_ordering
.end();
3725 Expression
** pexpr
= *p
;
3726 Location loc
= (*pexpr
)->location();
3728 if ((*pexpr
)->call_expression() == NULL
3729 || (*pexpr
)->call_expression()->result_count() < 2)
3731 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3734 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3738 // A call expression which returns multiple results needs to
3739 // be handled specially.
3740 s
= Statement::make_statement(*pexpr
, true);
3742 var
->add_preinit_statement(this->gogo_
, s
);
3745 if (init
!= orig_init
)
3746 var
->set_init(init
);
3748 return TRAVERSE_SKIP_COMPONENTS
;
3751 // Use temporary variables to implement the order of evaluation rules.
3754 Gogo::order_evaluations()
3756 Order_eval
order_eval(this);
3757 this->traverse(&order_eval
);
3760 // Traversal to flatten parse tree after order of evaluation rules are applied.
3762 class Flatten
: public Traverse
3765 Flatten(Gogo
* gogo
, Named_object
* function
)
3766 : Traverse(traverse_variables
3767 | traverse_functions
3768 | traverse_statements
3769 | traverse_expressions
),
3770 gogo_(gogo
), function_(function
), inserter_()
3774 set_inserter(const Statement_inserter
* inserter
)
3775 { this->inserter_
= *inserter
; }
3778 variable(Named_object
*);
3781 function(Named_object
*);
3784 statement(Block
*, size_t* pindex
, Statement
*);
3787 expression(Expression
**);
3792 // The function we are traversing.
3793 Named_object
* function_
;
3794 // Current statement inserter for use by expressions.
3795 Statement_inserter inserter_
;
3798 // Flatten variables.
3801 Flatten::variable(Named_object
* no
)
3803 if (!no
->is_variable())
3804 return TRAVERSE_CONTINUE
;
3806 if (no
->is_variable() && no
->var_value()->is_global())
3808 // Global variables can have loops in their initialization
3809 // expressions. This is handled in flatten_init_expression.
3810 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
3812 return TRAVERSE_CONTINUE
;
3815 go_assert(!no
->var_value()->has_pre_init());
3817 return TRAVERSE_SKIP_COMPONENTS
;
3820 // Flatten the body of a function. Record the function while flattening it,
3821 // so that we can pass it down when flattening an expression.
3824 Flatten::function(Named_object
* no
)
3826 go_assert(this->function_
== NULL
);
3827 this->function_
= no
;
3828 int t
= no
->func_value()->traverse(this);
3829 this->function_
= NULL
;
3831 if (t
== TRAVERSE_EXIT
)
3833 return TRAVERSE_SKIP_COMPONENTS
;
3836 // Flatten statement parse trees.
3839 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3841 // Because we explicitly traverse the statement's contents
3842 // ourselves, we want to skip block statements here. There is
3843 // nothing to flatten in a block statement.
3844 if (sorig
->is_block_statement())
3845 return TRAVERSE_CONTINUE
;
3847 Statement_inserter
hold_inserter(this->inserter_
);
3848 this->inserter_
= Statement_inserter(block
, pindex
);
3850 // Flatten the expressions first.
3851 int t
= sorig
->traverse_contents(this);
3852 if (t
== TRAVERSE_EXIT
)
3854 this->inserter_
= hold_inserter
;
3858 // Keep flattening until nothing changes.
3859 Statement
* s
= sorig
;
3862 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
3867 t
= s
->traverse_contents(this);
3868 if (t
== TRAVERSE_EXIT
)
3870 this->inserter_
= hold_inserter
;
3876 block
->replace_statement(*pindex
, s
);
3878 this->inserter_
= hold_inserter
;
3879 return TRAVERSE_SKIP_COMPONENTS
;
3882 // Flatten expression parse trees.
3885 Flatten::expression(Expression
** pexpr
)
3887 // Keep flattening until nothing changes.
3890 Expression
* e
= *pexpr
;
3891 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3892 return TRAVERSE_EXIT
;
3894 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
3900 return TRAVERSE_SKIP_COMPONENTS
;
3906 Gogo::flatten_block(Named_object
* function
, Block
* block
)
3908 Flatten
flatten(this, function
);
3909 block
->traverse(&flatten
);
3912 // Flatten an expression. INSERTER may be NULL, in which case the
3913 // expression had better not need to create any temporaries.
3916 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
3919 Flatten
flatten(this, function
);
3920 if (inserter
!= NULL
)
3921 flatten
.set_inserter(inserter
);
3922 flatten
.expression(pexpr
);
3928 Flatten
flatten(this, NULL
);
3929 this->traverse(&flatten
);
3932 // Traversal to convert calls to the predeclared recover function to
3933 // pass in an argument indicating whether it can recover from a panic
3936 class Convert_recover
: public Traverse
3939 Convert_recover(Named_object
* arg
)
3940 : Traverse(traverse_expressions
),
3946 expression(Expression
**);
3949 // The argument to pass to the function.
3953 // Convert calls to recover.
3956 Convert_recover::expression(Expression
** pp
)
3958 Call_expression
* ce
= (*pp
)->call_expression();
3959 if (ce
!= NULL
&& ce
->is_recover_call())
3960 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
3962 return TRAVERSE_CONTINUE
;
3965 // Traversal for build_recover_thunks.
3967 class Build_recover_thunks
: public Traverse
3970 Build_recover_thunks(Gogo
* gogo
)
3971 : Traverse(traverse_functions
),
3976 function(Named_object
*);
3980 can_recover_arg(Location
);
3986 // If this function calls recover, turn it into a thunk.
3989 Build_recover_thunks::function(Named_object
* orig_no
)
3991 Function
* orig_func
= orig_no
->func_value();
3992 if (!orig_func
->calls_recover()
3993 || orig_func
->is_recover_thunk()
3994 || orig_func
->has_recover_thunk())
3995 return TRAVERSE_CONTINUE
;
3997 Gogo
* gogo
= this->gogo_
;
3998 Location location
= orig_func
->location();
4003 Function_type
* orig_fntype
= orig_func
->type();
4004 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4005 std::string receiver_name
;
4006 if (orig_fntype
->is_method())
4008 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4009 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4011 receiver_name
= buf
;
4012 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4013 receiver
->location()));
4015 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4016 if (orig_params
!= NULL
&& !orig_params
->empty())
4018 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4019 p
!= orig_params
->end();
4022 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4024 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4028 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4030 std::string can_recover_name
= buf
;
4031 new_params
->push_back(Typed_identifier(can_recover_name
,
4032 Type::lookup_bool_type(),
4033 orig_fntype
->location()));
4035 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4036 Typed_identifier_list
* new_results
;
4037 if (orig_results
== NULL
|| orig_results
->empty())
4041 new_results
= new Typed_identifier_list();
4042 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4043 p
!= orig_results
->end();
4045 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4048 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4050 orig_fntype
->location());
4051 if (orig_fntype
->is_varargs())
4052 new_fntype
->set_is_varargs();
4054 std::string name
= orig_no
->name();
4055 if (orig_fntype
->is_method())
4056 name
+= "$" + orig_fntype
->receiver()->type()->mangled_name(gogo
);
4058 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4060 Function
*new_func
= new_no
->func_value();
4061 if (orig_func
->enclosing() != NULL
)
4062 new_func
->set_enclosing(orig_func
->enclosing());
4064 // We build the code for the original function attached to the new
4065 // function, and then swap the original and new function bodies.
4066 // This means that existing references to the original function will
4067 // then refer to the new function. That makes this code a little
4068 // confusing, in that the reference to NEW_NO really refers to the
4069 // other function, not the one we are building.
4071 Expression
* closure
= NULL
;
4072 if (orig_func
->needs_closure())
4074 // For the new function we are creating, declare a new parameter
4075 // variable NEW_CLOSURE_NO and set it to be the closure variable
4076 // of the function. This will be set to the closure value
4077 // passed in by the caller. Then pass a reference to this
4078 // variable as the closure value when calling the original
4079 // function. In other words, simply pass the closure value
4080 // through the thunk we are creating.
4081 Named_object
* orig_closure_no
= orig_func
->closure_var();
4082 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4083 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4084 false, false, location
);
4085 new_var
->set_is_closure();
4086 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4088 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4090 new_func
->set_closure_var(new_closure_no
);
4091 closure
= Expression::make_var_reference(new_closure_no
, location
);
4094 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4096 Expression_list
* args
= new Expression_list();
4097 if (new_params
!= NULL
)
4099 // Note that we skip the last parameter, which is the boolean
4100 // indicating whether recover can succed.
4101 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4102 p
+ 1 != new_params
->end();
4105 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4106 go_assert(p_no
!= NULL
4107 && p_no
->is_variable()
4108 && p_no
->var_value()->is_parameter());
4109 args
->push_back(Expression::make_var_reference(p_no
, location
));
4112 args
->push_back(this->can_recover_arg(location
));
4114 gogo
->start_block(location
);
4116 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4118 // Any varargs call has already been lowered.
4119 call
->set_varargs_are_lowered();
4121 Statement
* s
= Statement::make_return_from_call(call
, location
);
4122 s
->determine_types();
4123 gogo
->add_statement(s
);
4125 Block
* b
= gogo
->finish_block(location
);
4127 gogo
->add_block(b
, location
);
4129 // Lower the call in case it returns multiple results.
4130 gogo
->lower_block(new_no
, b
);
4132 gogo
->finish_function(location
);
4134 // Swap the function bodies and types.
4135 new_func
->swap_for_recover(orig_func
);
4136 orig_func
->set_is_recover_thunk();
4137 new_func
->set_calls_recover();
4138 new_func
->set_has_recover_thunk();
4140 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4141 Bindings
* new_bindings
= new_func
->block()->bindings();
4142 if (orig_fntype
->is_method())
4144 // We changed the receiver to be a regular parameter. We have
4145 // to update the binding accordingly in both functions.
4146 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4147 go_assert(orig_rec_no
!= NULL
4148 && orig_rec_no
->is_variable()
4149 && !orig_rec_no
->var_value()->is_receiver());
4150 orig_rec_no
->var_value()->set_is_receiver();
4152 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4153 if (new_receiver_name
.empty())
4155 // Find the receiver. It was named "r.NNN" in
4156 // Gogo::start_function.
4157 for (Bindings::const_definitions_iterator p
=
4158 new_bindings
->begin_definitions();
4159 p
!= new_bindings
->end_definitions();
4162 const std::string
& pname((*p
)->name());
4163 if (pname
[0] == 'r' && pname
[1] == '.')
4165 new_receiver_name
= pname
;
4169 go_assert(!new_receiver_name
.empty());
4171 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4172 if (new_rec_no
== NULL
)
4173 go_assert(saw_errors());
4176 go_assert(new_rec_no
->is_variable()
4177 && new_rec_no
->var_value()->is_receiver());
4178 new_rec_no
->var_value()->set_is_not_receiver();
4182 // Because we flipped blocks but not types, the can_recover
4183 // parameter appears in the (now) old bindings as a parameter.
4184 // Change it to a local variable, whereupon it will be discarded.
4185 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4186 go_assert(can_recover_no
!= NULL
4187 && can_recover_no
->is_variable()
4188 && can_recover_no
->var_value()->is_parameter());
4189 orig_bindings
->remove_binding(can_recover_no
);
4191 // Add the can_recover argument to the (now) new bindings, and
4192 // attach it to any recover statements.
4193 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4194 false, true, false, location
);
4195 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4197 Convert_recover
convert_recover(can_recover_no
);
4198 new_func
->traverse(&convert_recover
);
4200 // Update the function pointers in any named results.
4201 new_func
->update_result_variables();
4202 orig_func
->update_result_variables();
4204 return TRAVERSE_CONTINUE
;
4207 // Return the expression to pass for the .can_recover parameter to the
4208 // new function. This indicates whether a call to recover may return
4209 // non-nil. The expression is
4210 // __go_can_recover(__builtin_return_address()).
4213 Build_recover_thunks::can_recover_arg(Location location
)
4215 static Named_object
* builtin_return_address
;
4216 if (builtin_return_address
== NULL
)
4218 const Location bloc
= Linemap::predeclared_location();
4220 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4221 Type
* uint_type
= Type::lookup_integer_type("uint");
4222 param_types
->push_back(Typed_identifier("l", uint_type
, bloc
));
4224 Typed_identifier_list
* return_types
= new Typed_identifier_list();
4225 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4226 return_types
->push_back(Typed_identifier("", voidptr_type
, bloc
));
4228 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4229 return_types
, bloc
);
4230 builtin_return_address
=
4231 Named_object::make_function_declaration("__builtin_return_address",
4232 NULL
, fntype
, bloc
);
4233 const char* n
= "__builtin_return_address";
4234 builtin_return_address
->func_declaration_value()->set_asm_name(n
);
4237 static Named_object
* can_recover
;
4238 if (can_recover
== NULL
)
4240 const Location bloc
= Linemap::predeclared_location();
4241 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4242 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4243 param_types
->push_back(Typed_identifier("a", voidptr_type
, bloc
));
4244 Type
* boolean_type
= Type::lookup_bool_type();
4245 Typed_identifier_list
* results
= new Typed_identifier_list();
4246 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4247 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4249 can_recover
= Named_object::make_function_declaration("__go_can_recover",
4252 can_recover
->func_declaration_value()->set_asm_name("__go_can_recover");
4255 Expression
* fn
= Expression::make_func_reference(builtin_return_address
,
4258 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4259 Expression_list
*args
= new Expression_list();
4260 args
->push_back(zexpr
);
4262 Expression
* call
= Expression::make_call(fn
, args
, false, location
);
4264 args
= new Expression_list();
4265 args
->push_back(call
);
4267 fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4268 return Expression::make_call(fn
, args
, false, location
);
4271 // Build thunks for functions which call recover. We build a new
4272 // function with an extra parameter, which is whether a call to
4273 // recover can succeed. We then move the body of this function to
4274 // that one. We then turn this function into a thunk which calls the
4275 // new one, passing the value of
4276 // __go_can_recover(__builtin_return_address()). The function will be
4277 // marked as not splitting the stack. This will cooperate with the
4278 // implementation of defer to make recover do the right thing.
4281 Gogo::build_recover_thunks()
4283 Build_recover_thunks
build_recover_thunks(this);
4284 this->traverse(&build_recover_thunks
);
4287 // Build a call to the runtime error function.
4290 Gogo::runtime_error(int code
, Location location
)
4292 Type
* int32_type
= Type::lookup_integer_type("int32");
4293 Expression
* code_expr
= Expression::make_integer_ul(code
, int32_type
,
4295 return Runtime::make_call(Runtime::RUNTIME_ERROR
, location
, 1, code_expr
);
4298 // Look for named types to see whether we need to create an interface
4301 class Build_method_tables
: public Traverse
4304 Build_method_tables(Gogo
* gogo
,
4305 const std::vector
<Interface_type
*>& interfaces
)
4306 : Traverse(traverse_types
),
4307 gogo_(gogo
), interfaces_(interfaces
)
4316 // A list of locally defined interfaces which have hidden methods.
4317 const std::vector
<Interface_type
*>& interfaces_
;
4320 // Build all required interface method tables for types. We need to
4321 // ensure that we have an interface method table for every interface
4322 // which has a hidden method, for every named type which implements
4323 // that interface. Normally we can just build interface method tables
4324 // as we need them. However, in some cases we can require an
4325 // interface method table for an interface defined in a different
4326 // package for a type defined in that package. If that interface and
4327 // type both use a hidden method, that is OK. However, we will not be
4328 // able to build that interface method table when we need it, because
4329 // the type's hidden method will be static. So we have to build it
4330 // here, and just refer it from other packages as needed.
4333 Gogo::build_interface_method_tables()
4338 std::vector
<Interface_type
*> hidden_interfaces
;
4339 hidden_interfaces
.reserve(this->interface_types_
.size());
4340 for (std::vector
<Interface_type
*>::const_iterator pi
=
4341 this->interface_types_
.begin();
4342 pi
!= this->interface_types_
.end();
4345 const Typed_identifier_list
* methods
= (*pi
)->methods();
4346 if (methods
== NULL
)
4348 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4349 pm
!= methods
->end();
4352 if (Gogo::is_hidden_name(pm
->name()))
4354 hidden_interfaces
.push_back(*pi
);
4360 if (!hidden_interfaces
.empty())
4362 // Now traverse the tree looking for all named types.
4363 Build_method_tables
bmt(this, hidden_interfaces
);
4364 this->traverse(&bmt
);
4367 // We no longer need the list of interfaces.
4369 this->interface_types_
.clear();
4372 // This is called for each type. For a named type, for each of the
4373 // interfaces with hidden methods that it implements, create the
4377 Build_method_tables::type(Type
* type
)
4379 Named_type
* nt
= type
->named_type();
4380 Struct_type
* st
= type
->struct_type();
4381 if (nt
!= NULL
|| st
!= NULL
)
4383 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4384 for (std::vector
<Interface_type
*>::const_iterator p
=
4385 this->interfaces_
.begin();
4386 p
!= this->interfaces_
.end();
4389 // We ask whether a pointer to the named type implements the
4390 // interface, because a pointer can implement more methods
4394 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4397 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4398 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4403 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4406 st
->interface_method_table(*p
, false)->get_backend(&context
);
4407 st
->interface_method_table(*p
, true)->get_backend(&context
);
4412 return TRAVERSE_CONTINUE
;
4415 // Return an expression which allocates memory to hold values of type TYPE.
4418 Gogo::allocate_memory(Type
* type
, Location location
)
4420 Expression
* td
= Expression::make_type_descriptor(type
, location
);
4422 Expression::make_type_info(type
, Expression::TYPE_INFO_SIZE
);
4423 return Runtime::make_call(Runtime::NEW
, location
, 2, td
, size
);
4426 // Traversal class used to check for return statements.
4428 class Check_return_statements_traverse
: public Traverse
4431 Check_return_statements_traverse()
4432 : Traverse(traverse_functions
)
4436 function(Named_object
*);
4439 // Check that a function has a return statement if it needs one.
4442 Check_return_statements_traverse::function(Named_object
* no
)
4444 Function
* func
= no
->func_value();
4445 const Function_type
* fntype
= func
->type();
4446 const Typed_identifier_list
* results
= fntype
->results();
4448 // We only need a return statement if there is a return value.
4449 if (results
== NULL
|| results
->empty())
4450 return TRAVERSE_CONTINUE
;
4452 if (func
->block()->may_fall_through())
4453 error_at(func
->block()->end_location(),
4454 "missing return at end of function");
4456 return TRAVERSE_CONTINUE
;
4459 // Check return statements.
4462 Gogo::check_return_statements()
4464 Check_return_statements_traverse traverse
;
4465 this->traverse(&traverse
);
4468 // Work out the package priority. It is one more than the maximum
4469 // priority of an imported package.
4472 Gogo::package_priority() const
4475 for (Packages::const_iterator p
= this->packages_
.begin();
4476 p
!= this->packages_
.end();
4478 if (p
->second
->priority() > priority
)
4479 priority
= p
->second
->priority();
4480 return priority
+ 1;
4483 // Export identifiers as requested.
4488 // For now we always stream to a section. Later we may want to
4489 // support streaming to a separate file.
4490 Stream_to_section stream
;
4492 // Write out either the prefix or pkgpath depending on how we were
4495 std::string pkgpath
;
4496 if (this->pkgpath_from_option_
)
4497 pkgpath
= this->pkgpath_
;
4498 else if (this->prefix_from_option_
)
4499 prefix
= this->prefix_
;
4500 else if (this->is_main_package())
4505 Export
exp(&stream
);
4506 exp
.register_builtin_types(this);
4507 exp
.export_globals(this->package_name(),
4510 this->package_priority(),
4513 (this->need_init_fn_
&& !this->is_main_package()
4514 ? this->get_init_fn_name()
4516 this->imported_init_fns_
,
4517 this->package_
->bindings());
4520 // Find the blocks in order to convert named types defined in blocks.
4522 class Convert_named_types
: public Traverse
4525 Convert_named_types(Gogo
* gogo
)
4526 : Traverse(traverse_blocks
),
4532 block(Block
* block
);
4539 Convert_named_types::block(Block
* block
)
4541 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
4542 return TRAVERSE_CONTINUE
;
4545 // Convert all named types to the backend representation. Since named
4546 // types can refer to other types, this needs to be done in the right
4547 // sequence, which is handled by Named_type::convert. Here we arrange
4548 // to call that for each named type.
4551 Gogo::convert_named_types()
4553 this->convert_named_types_in_bindings(this->globals_
);
4554 for (Packages::iterator p
= this->packages_
.begin();
4555 p
!= this->packages_
.end();
4558 Package
* package
= p
->second
;
4559 this->convert_named_types_in_bindings(package
->bindings());
4562 Convert_named_types
cnt(this);
4563 this->traverse(&cnt
);
4565 // Make all the builtin named types used for type descriptors, and
4566 // then convert them. They will only be written out if they are
4568 Type::make_type_descriptor_type();
4569 Type::make_type_descriptor_ptr_type();
4570 Function_type::make_function_type_descriptor_type();
4571 Pointer_type::make_pointer_type_descriptor_type();
4572 Struct_type::make_struct_type_descriptor_type();
4573 Array_type::make_array_type_descriptor_type();
4574 Array_type::make_slice_type_descriptor_type();
4575 Map_type::make_map_type_descriptor_type();
4576 Map_type::make_map_descriptor_type();
4577 Channel_type::make_chan_type_descriptor_type();
4578 Interface_type::make_interface_type_descriptor_type();
4579 Expression::make_func_descriptor_type();
4580 Type::convert_builtin_named_types(this);
4582 Runtime::convert_types(this);
4584 this->named_types_are_converted_
= true;
4587 // Convert all names types in a set of bindings.
4590 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
4592 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
4593 p
!= bindings
->end_definitions();
4596 if ((*p
)->is_type())
4597 (*p
)->type_value()->convert(this);
4603 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
4605 : type_(type
), enclosing_(enclosing
), results_(NULL
),
4606 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
4607 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
4608 is_sink_(false), results_are_named_(false), nointerface_(false),
4609 is_unnamed_type_stub_method_(false), calls_recover_(false),
4610 is_recover_thunk_(false), has_recover_thunk_(false),
4611 calls_defer_retaddr_(false), is_type_specific_function_(false),
4612 in_unique_section_(false)
4616 // Create the named result variables.
4619 Function::create_result_variables(Gogo
* gogo
)
4621 const Typed_identifier_list
* results
= this->type_
->results();
4622 if (results
== NULL
|| results
->empty())
4625 if (!results
->front().name().empty())
4626 this->results_are_named_
= true;
4628 this->results_
= new Results();
4629 this->results_
->reserve(results
->size());
4631 Block
* block
= this->block_
;
4633 for (Typed_identifier_list::const_iterator p
= results
->begin();
4634 p
!= results
->end();
4637 std::string name
= p
->name();
4638 if (name
.empty() || Gogo::is_sink_name(name
))
4640 static int result_counter
;
4642 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
4644 name
= gogo
->pack_hidden_name(buf
, false);
4646 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
4648 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
4649 if (no
->is_result_variable())
4650 this->results_
->push_back(no
);
4653 static int dummy_result_count
;
4655 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
4656 ++dummy_result_count
;
4657 name
= gogo
->pack_hidden_name(buf
, false);
4658 no
= block
->bindings()->add_result_variable(name
, result
);
4659 go_assert(no
->is_result_variable());
4660 this->results_
->push_back(no
);
4665 // Update the named result variables when cloning a function which
4669 Function::update_result_variables()
4671 if (this->results_
== NULL
)
4674 for (Results::iterator p
= this->results_
->begin();
4675 p
!= this->results_
->end();
4677 (*p
)->result_var_value()->set_function(this);
4680 // Return the closure variable, creating it if necessary.
4683 Function::closure_var()
4685 if (this->closure_var_
== NULL
)
4687 go_assert(this->descriptor_
== NULL
);
4688 // We don't know the type of the variable yet. We add fields as
4690 Location loc
= this->type_
->location();
4691 Struct_field_list
* sfl
= new Struct_field_list
;
4692 Type
* struct_type
= Type::make_struct_type(sfl
, loc
);
4693 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
4694 NULL
, false, false, false, loc
);
4696 var
->set_is_closure();
4697 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
4698 // Note that the new variable is not in any binding contour.
4700 return this->closure_var_
;
4703 // Set the type of the closure variable.
4706 Function::set_closure_type()
4708 if (this->closure_var_
== NULL
)
4710 Named_object
* closure
= this->closure_var_
;
4711 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
4713 // The first field of a closure is always a pointer to the function
4715 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4716 st
->push_field(Struct_field(Typed_identifier(".$f", voidptr_type
,
4719 unsigned int index
= 1;
4720 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
4721 p
!= this->closure_fields_
.end();
4724 Named_object
* no
= p
->first
;
4726 snprintf(buf
, sizeof buf
, "%u", index
);
4727 std::string n
= no
->name() + buf
;
4729 if (no
->is_variable())
4730 var_type
= no
->var_value()->type();
4732 var_type
= no
->result_var_value()->type();
4733 Type
* field_type
= Type::make_pointer_type(var_type
);
4734 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
4738 // Return whether this function is a method.
4741 Function::is_method() const
4743 return this->type_
->is_method();
4746 // Add a label definition.
4749 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
4752 Label
* lnull
= NULL
;
4753 std::pair
<Labels::iterator
, bool> ins
=
4754 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4756 if (label_name
== "_")
4758 label
= Label::create_dummy_label();
4760 ins
.first
->second
= label
;
4762 else if (ins
.second
)
4764 // This is a new label.
4765 label
= new Label(label_name
);
4766 ins
.first
->second
= label
;
4770 // The label was already in the hash table.
4771 label
= ins
.first
->second
;
4772 if (label
->is_defined())
4774 error_at(location
, "label %qs already defined",
4775 Gogo::message_name(label_name
).c_str());
4776 inform(label
->location(), "previous definition of %qs was here",
4777 Gogo::message_name(label_name
).c_str());
4778 return new Label(label_name
);
4782 label
->define(location
, gogo
->bindings_snapshot(location
));
4784 // Issue any errors appropriate for any previous goto's to this
4786 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
4787 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
4790 (*p
)->check_goto_to(gogo
->current_block());
4791 label
->clear_refs();
4796 // Add a reference to a label.
4799 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
4800 Location location
, bool issue_goto_errors
)
4802 Label
* lnull
= NULL
;
4803 std::pair
<Labels::iterator
, bool> ins
=
4804 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4808 // The label was already in the hash table.
4809 label
= ins
.first
->second
;
4813 go_assert(ins
.first
->second
== NULL
);
4814 label
= new Label(label_name
);
4815 ins
.first
->second
= label
;
4818 label
->set_is_used();
4820 if (issue_goto_errors
)
4822 Bindings_snapshot
* snapshot
= label
->snapshot();
4823 if (snapshot
!= NULL
)
4824 snapshot
->check_goto_from(gogo
->current_block(), location
);
4826 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
4832 // Warn about labels that are defined but not used.
4835 Function::check_labels() const
4837 for (Labels::const_iterator p
= this->labels_
.begin();
4838 p
!= this->labels_
.end();
4841 Label
* label
= p
->second
;
4842 if (!label
->is_used())
4843 error_at(label
->location(), "label %qs defined and not used",
4844 Gogo::message_name(label
->name()).c_str());
4848 // Swap one function with another. This is used when building the
4849 // thunk we use to call a function which calls recover. It may not
4850 // work for any other case.
4853 Function::swap_for_recover(Function
*x
)
4855 go_assert(this->enclosing_
== x
->enclosing_
);
4856 std::swap(this->results_
, x
->results_
);
4857 std::swap(this->closure_var_
, x
->closure_var_
);
4858 std::swap(this->block_
, x
->block_
);
4859 go_assert(this->location_
== x
->location_
);
4860 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
4861 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
4864 // Traverse the tree.
4867 Function::traverse(Traverse
* traverse
)
4869 unsigned int traverse_mask
= traverse
->traverse_mask();
4872 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
4875 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
4876 return TRAVERSE_EXIT
;
4879 // FIXME: We should check traverse_functions here if nested
4880 // functions are stored in block bindings.
4881 if (this->block_
!= NULL
4883 & (Traverse::traverse_variables
4884 | Traverse::traverse_constants
4885 | Traverse::traverse_blocks
4886 | Traverse::traverse_statements
4887 | Traverse::traverse_expressions
4888 | Traverse::traverse_types
)) != 0)
4890 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
4891 return TRAVERSE_EXIT
;
4894 return TRAVERSE_CONTINUE
;
4897 // Work out types for unspecified variables and constants.
4900 Function::determine_types()
4902 if (this->block_
!= NULL
)
4903 this->block_
->determine_types();
4906 // Return the function descriptor, the value you get when you refer to
4907 // the function in Go code without calling it.
4910 Function::descriptor(Gogo
*, Named_object
* no
)
4912 go_assert(!this->is_method());
4913 go_assert(this->closure_var_
== NULL
);
4914 if (this->descriptor_
== NULL
)
4915 this->descriptor_
= Expression::make_func_descriptor(no
);
4916 return this->descriptor_
;
4919 // Get a pointer to the variable representing the defer stack for this
4920 // function, making it if necessary. The value of the variable is set
4921 // by the runtime routines to true if the function is returning,
4922 // rather than panicing through. A pointer to this variable is used
4923 // as a marker for the functions on the defer stack associated with
4924 // this function. A function-specific variable permits inlining a
4925 // function which uses defer.
4928 Function::defer_stack(Location location
)
4930 if (this->defer_stack_
== NULL
)
4932 Type
* t
= Type::lookup_bool_type();
4933 Expression
* n
= Expression::make_boolean(false, location
);
4934 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
4935 this->defer_stack_
->set_is_address_taken();
4937 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
4939 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
4942 // Export the function.
4945 Function::export_func(Export
* exp
, const std::string
& name
) const
4947 Function::export_func_with_type(exp
, name
, this->type_
);
4950 // Export a function with a type.
4953 Function::export_func_with_type(Export
* exp
, const std::string
& name
,
4954 const Function_type
* fntype
)
4956 exp
->write_c_string("func ");
4958 if (fntype
->is_method())
4960 exp
->write_c_string("(");
4961 const Typed_identifier
* receiver
= fntype
->receiver();
4962 exp
->write_name(receiver
->name());
4964 if (fntype
->has_escape_info())
4966 exp
->write_c_string(" ");
4967 exp
->write_escape(fntype
->receiver_escape_state());
4970 exp
->write_c_string(" ");
4971 exp
->write_type(receiver
->type());
4972 exp
->write_c_string(") ");
4975 exp
->write_string(name
);
4977 exp
->write_c_string(" (");
4978 const Typed_identifier_list
* parameters
= fntype
->parameters();
4979 if (parameters
!= NULL
)
4982 bool is_varargs
= fntype
->is_varargs();
4984 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
4985 p
!= parameters
->end();
4991 exp
->write_c_string(", ");
4992 exp
->write_name(p
->name());
4994 if (fntype
->has_escape_info())
4996 exp
->write_c_string(" ");
4997 exp
->write_escape(fntype
->parameter_escape_states()->at(i
));
5000 exp
->write_c_string(" ");
5001 if (!is_varargs
|| p
+ 1 != parameters
->end())
5002 exp
->write_type(p
->type());
5005 exp
->write_c_string("...");
5006 exp
->write_type(p
->type()->array_type()->element_type());
5010 exp
->write_c_string(")");
5012 const Typed_identifier_list
* results
= fntype
->results();
5013 if (results
!= NULL
)
5015 if (results
->size() == 1 && results
->begin()->name().empty())
5017 exp
->write_c_string(" ");
5018 exp
->write_type(results
->begin()->type());
5022 exp
->write_c_string(" (");
5024 for (Typed_identifier_list::const_iterator p
= results
->begin();
5025 p
!= results
->end();
5031 exp
->write_c_string(", ");
5032 exp
->write_name(p
->name());
5033 exp
->write_c_string(" ");
5034 exp
->write_type(p
->type());
5036 exp
->write_c_string(")");
5039 exp
->write_c_string(";\n");
5042 // Import a function.
5045 Function::import_func(Import
* imp
, std::string
* pname
,
5046 Typed_identifier
** preceiver
,
5047 Node::Escapement_lattice
* rcvr_escape
,
5048 Typed_identifier_list
** pparameters
,
5049 Node::Escape_states
** pparam_escapes
,
5050 Typed_identifier_list
** presults
,
5051 bool* is_varargs
, bool* has_escape_info
)
5053 *has_escape_info
= false;
5055 imp
->require_c_string("func ");
5058 *rcvr_escape
= Node::ESCAPE_NONE
;
5059 if (imp
->peek_char() == '(')
5061 imp
->require_c_string("(");
5062 std::string name
= imp
->read_name();
5064 if (imp
->match_c_string(" <escape")){
5065 *has_escape_info
= true;
5066 imp
->require_c_string(" ");
5067 *rcvr_escape
= imp
->read_escape_info();
5070 imp
->require_c_string(" ");
5071 Type
* rtype
= imp
->read_type();
5072 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
5073 imp
->require_c_string(") ");
5076 *pname
= imp
->read_identifier();
5078 Typed_identifier_list
* parameters
;
5079 Node::Escape_states
* param_escapes
;
5080 *is_varargs
= false;
5081 imp
->require_c_string(" (");
5082 if (imp
->peek_char() == ')')
5085 param_escapes
= NULL
;
5089 parameters
= new Typed_identifier_list();
5090 param_escapes
= new Node::Escape_states();
5093 std::string name
= imp
->read_name();
5094 if (imp
->match_c_string(" <escape")){
5095 *has_escape_info
= true;
5096 imp
->require_c_string(" ");
5097 param_escapes
->push_back(imp
->read_escape_info());
5100 imp
->require_c_string(" ");
5102 if (imp
->match_c_string("..."))
5108 Type
* ptype
= imp
->read_type();
5110 ptype
= Type::make_array_type(ptype
, NULL
);
5111 parameters
->push_back(Typed_identifier(name
, ptype
,
5113 if (imp
->peek_char() != ',')
5115 go_assert(!*is_varargs
);
5116 imp
->require_c_string(", ");
5119 imp
->require_c_string(")");
5120 *pparameters
= parameters
;
5121 *pparam_escapes
= param_escapes
;
5123 Typed_identifier_list
* results
;
5124 if (imp
->peek_char() != ' ')
5128 results
= new Typed_identifier_list();
5129 imp
->require_c_string(" ");
5130 if (imp
->peek_char() != '(')
5132 Type
* rtype
= imp
->read_type();
5133 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
5137 imp
->require_c_string("(");
5140 std::string name
= imp
->read_name();
5141 imp
->require_c_string(" ");
5142 Type
* rtype
= imp
->read_type();
5143 results
->push_back(Typed_identifier(name
, rtype
,
5145 if (imp
->peek_char() != ',')
5147 imp
->require_c_string(", ");
5149 imp
->require_c_string(")");
5152 imp
->require_c_string(";\n");
5153 *presults
= results
;
5156 // Get the backend representation.
5159 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5161 if (this->fndecl_
== NULL
)
5163 std::string asm_name
;
5164 bool is_visible
= false;
5165 if (no
->package() != NULL
)
5167 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
5169 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
5170 && !this->type_
->is_method())
5172 else if (no
->name() == gogo
->get_init_fn_name())
5175 asm_name
= no
->name();
5177 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
5178 && gogo
->is_main_package())
5180 // Methods have to be public even if they are hidden because
5181 // they can be pulled into type descriptors when using
5182 // anonymous fields.
5183 else if (!Gogo::is_hidden_name(no
->name())
5184 || this->type_
->is_method())
5186 if (!this->is_unnamed_type_stub_method_
)
5188 std::string pkgpath
= gogo
->pkgpath_symbol();
5189 if (this->type_
->is_method()
5190 && Gogo::is_hidden_name(no
->name())
5191 && Gogo::hidden_name_pkgpath(no
->name()) != gogo
->pkgpath())
5193 // This is a method we created for an unexported
5194 // method of an imported embedded type. We need to
5195 // use the pkgpath of the imported package to avoid
5196 // a possible name collision. See bug478 for a test
5198 pkgpath
= Gogo::hidden_name_pkgpath(no
->name());
5199 pkgpath
= Gogo::pkgpath_for_symbol(pkgpath
);
5203 asm_name
.append(1, '.');
5204 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5205 if (this->type_
->is_method())
5207 asm_name
.append(1, '.');
5208 Type
* rtype
= this->type_
->receiver()->type();
5209 asm_name
.append(rtype
->mangled_name(gogo
));
5213 // If a function calls the predeclared recover function, we
5214 // can't inline it, because recover behaves differently in a
5215 // function passed directly to defer. If this is a recover
5216 // thunk that we built to test whether a function can be
5217 // recovered, we can't inline it, because that will mess up
5218 // our return address comparison.
5219 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
5221 // If a function calls __go_set_defer_retaddr, then mark it as
5222 // uninlinable. This prevents the GCC backend from splitting
5223 // the function; splitting the function is a bad idea because we
5224 // want the return address label to be in the same function as
5226 if (this->calls_defer_retaddr_
)
5227 is_inlinable
= false;
5229 // If this is a thunk created to call a function which calls
5230 // the predeclared recover function, we need to disable
5231 // stack splitting for the thunk.
5232 bool disable_split_stack
= this->is_recover_thunk_
;
5234 // This should go into a unique section if that has been
5235 // requested elsewhere, or if this is a nointerface function.
5236 // We want to put a nointerface function into a unique section
5237 // because there is a good chance that the linker garbage
5238 // collection can discard it.
5239 bool in_unique_section
= this->in_unique_section_
|| this->nointerface_
;
5241 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
5243 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5244 is_visible
, false, is_inlinable
,
5245 disable_split_stack
, in_unique_section
,
5248 return this->fndecl_
;
5251 // Get the backend representation.
5254 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5256 if (this->fndecl_
== NULL
)
5258 // Let Go code use an asm declaration to pick up a builtin
5260 if (!this->asm_name_
.empty())
5262 Bfunction
* builtin_decl
=
5263 gogo
->backend()->lookup_builtin(this->asm_name_
);
5264 if (builtin_decl
!= NULL
)
5266 this->fndecl_
= builtin_decl
;
5267 return this->fndecl_
;
5271 std::string asm_name
;
5272 if (this->asm_name_
.empty())
5274 asm_name
= (no
->package() == NULL
5275 ? gogo
->pkgpath_symbol()
5276 : no
->package()->pkgpath_symbol());
5277 asm_name
.append(1, '.');
5278 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5279 if (this->fntype_
->is_method())
5281 asm_name
.append(1, '.');
5282 Type
* rtype
= this->fntype_
->receiver()->type();
5283 asm_name
.append(rtype
->mangled_name(gogo
));
5287 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
5289 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5290 true, true, true, false, false,
5294 return this->fndecl_
;
5297 // Build the descriptor for a function declaration. This won't
5298 // necessarily happen if the package has just a declaration for the
5299 // function and no other reference to it, but we may still need the
5300 // descriptor for references from other packages.
5302 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
5304 if (this->descriptor_
!= NULL
)
5306 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5307 this->descriptor_
->get_backend(&context
);
5311 // Check that the types used in this declaration's signature are defined.
5312 // Reports errors for any undefined type.
5315 Function_declaration::check_types() const
5317 // Calling Type::base will give errors for any undefined types.
5318 Function_type
* fntype
= this->type();
5319 if (fntype
->receiver() != NULL
)
5320 fntype
->receiver()->type()->base();
5321 if (fntype
->parameters() != NULL
)
5323 const Typed_identifier_list
* params
= fntype
->parameters();
5324 for (Typed_identifier_list::const_iterator p
= params
->begin();
5331 // Return the function's decl after it has been built.
5334 Function::get_decl() const
5336 go_assert(this->fndecl_
!= NULL
);
5337 return this->fndecl_
;
5340 // Build the backend representation for the function code.
5343 Function::build(Gogo
* gogo
, Named_object
* named_function
)
5345 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5347 // A list of parameter variables for this function.
5348 std::vector
<Bvariable
*> param_vars
;
5350 // Variables that need to be declared for this function and their
5352 std::vector
<Bvariable
*> vars
;
5353 std::vector
<Bexpression
*> var_inits
;
5354 for (Bindings::const_definitions_iterator p
=
5355 this->block_
->bindings()->begin_definitions();
5356 p
!= this->block_
->bindings()->end_definitions();
5359 Location loc
= (*p
)->location();
5360 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
5362 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5363 Bvariable
* parm_bvar
= bvar
;
5365 // We always pass the receiver to a method as a pointer. If
5366 // the receiver is declared as a non-pointer type, then we
5367 // copy the value into a local variable.
5368 if ((*p
)->var_value()->is_receiver()
5369 && (*p
)->var_value()->type()->points_to() == NULL
)
5371 std::string name
= (*p
)->name() + ".pointer";
5372 Type
* var_type
= (*p
)->var_value()->type();
5373 Variable
* parm_var
=
5374 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
5376 Named_object
* parm_no
=
5377 Named_object::make_variable(name
, NULL
, parm_var
);
5378 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5380 vars
.push_back(bvar
);
5381 Expression
* parm_ref
=
5382 Expression::make_var_reference(parm_no
, loc
);
5383 parm_ref
= Expression::make_unary(OPERATOR_MULT
, parm_ref
, loc
);
5384 if ((*p
)->var_value()->is_in_heap())
5385 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
5386 var_inits
.push_back(parm_ref
->get_backend(&context
));
5388 else if ((*p
)->var_value()->is_in_heap())
5390 // If we take the address of a parameter, then we need
5391 // to copy it into the heap.
5392 std::string parm_name
= (*p
)->name() + ".param";
5393 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
5394 false, true, false, loc
);
5395 Named_object
* parm_no
=
5396 Named_object::make_variable(parm_name
, NULL
, parm_var
);
5397 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5399 vars
.push_back(bvar
);
5400 Expression
* var_ref
=
5401 Expression::make_var_reference(parm_no
, loc
);
5402 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
5403 var_inits
.push_back(var_ref
->get_backend(&context
));
5405 param_vars
.push_back(parm_bvar
);
5407 else if ((*p
)->is_result_variable())
5409 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5411 Type
* type
= (*p
)->result_var_value()->type();
5413 if (!(*p
)->result_var_value()->is_in_heap())
5415 Btype
* btype
= type
->get_backend(gogo
);
5416 init
= gogo
->backend()->zero_expression(btype
);
5419 init
= Expression::make_allocation(type
,
5420 loc
)->get_backend(&context
);
5422 vars
.push_back(bvar
);
5423 var_inits
.push_back(init
);
5426 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
5428 go_assert(saw_errors());
5432 // If we need a closure variable, make sure to create it.
5433 // It gets installed in the function as a side effect of creation.
5434 if (this->closure_var_
!= NULL
)
5436 go_assert(this->closure_var_
->var_value()->is_closure());
5437 this->closure_var_
->get_backend_variable(gogo
, named_function
);
5440 if (this->block_
!= NULL
)
5442 // Declare variables if necessary.
5443 Bblock
* var_decls
= NULL
;
5445 Bstatement
* defer_init
= NULL
;
5446 if (!vars
.empty() || this->defer_stack_
!= NULL
)
5449 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
5450 this->block_
->start_location(),
5451 this->block_
->end_location());
5453 if (this->defer_stack_
!= NULL
)
5455 Translate_context
dcontext(gogo
, named_function
, this->block_
,
5457 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
5461 // Build the backend representation for all the statements in the
5463 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5464 Bblock
* code_block
= this->block_
->get_backend(&context
);
5466 // Initialize variables if necessary.
5467 std::vector
<Bstatement
*> init
;
5468 go_assert(vars
.size() == var_inits
.size());
5469 for (size_t i
= 0; i
< vars
.size(); ++i
)
5471 Bstatement
* init_stmt
=
5472 gogo
->backend()->init_statement(vars
[i
], var_inits
[i
]);
5473 init
.push_back(init_stmt
);
5475 if (defer_init
!= NULL
)
5476 init
.push_back(defer_init
);
5477 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
5479 // Initialize all variables before executing this code block.
5480 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
5481 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
5483 // If we have a defer stack, initialize it at the start of a
5485 Bstatement
* except
= NULL
;
5486 Bstatement
* fini
= NULL
;
5487 if (defer_init
!= NULL
)
5489 // Clean up the defer stack when we leave the function.
5490 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
5492 // Wrap the code for this function in an exception handler to handle
5495 gogo
->backend()->exception_handler_statement(code_stmt
,
5500 // Stick the code into the block we built for the receiver, if
5502 if (var_decls
!= NULL
)
5504 std::vector
<Bstatement
*> code_stmt_list(1, code_stmt
);
5505 gogo
->backend()->block_add_statements(var_decls
, code_stmt_list
);
5506 code_stmt
= gogo
->backend()->block_statement(var_decls
);
5509 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
5511 go_assert(saw_errors());
5516 // If we created a descriptor for the function, make sure we emit it.
5517 if (this->descriptor_
!= NULL
)
5519 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5520 this->descriptor_
->get_backend(&context
);
5524 // Build the wrappers around function code needed if the function has
5525 // any defer statements. This sets *EXCEPT to an exception handler
5526 // and *FINI to a finally handler.
5529 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
5530 Bstatement
** except
, Bstatement
** fini
)
5532 Location end_loc
= this->block_
->end_location();
5534 // Add an exception handler. This is used if a panic occurs. Its
5535 // purpose is to stop the stack unwinding if a deferred function
5536 // calls recover. There are more details in
5537 // libgo/runtime/go-unwind.c.
5539 std::vector
<Bstatement
*> stmts
;
5540 Expression
* call
= Runtime::make_call(Runtime::CHECK_DEFER
, end_loc
, 1,
5541 this->defer_stack(end_loc
));
5542 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5543 Bexpression
* defer
= call
->get_backend(&context
);
5544 stmts
.push_back(gogo
->backend()->expression_statement(defer
));
5546 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5547 if (ret_bstmt
!= NULL
)
5548 stmts
.push_back(ret_bstmt
);
5550 go_assert(*except
== NULL
);
5551 *except
= gogo
->backend()->statement_list(stmts
);
5553 call
= Runtime::make_call(Runtime::CHECK_DEFER
, end_loc
, 1,
5554 this->defer_stack(end_loc
));
5555 defer
= call
->get_backend(&context
);
5557 call
= Runtime::make_call(Runtime::UNDEFER
, end_loc
, 1,
5558 this->defer_stack(end_loc
));
5559 Bexpression
* undefer
= call
->get_backend(&context
);
5560 Bstatement
* function_defer
=
5561 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
5563 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
5564 if (this->type_
->results() != NULL
5565 && !this->type_
->results()->empty()
5566 && !this->type_
->results()->front().name().empty())
5568 // If the result variables are named, and we are returning from
5569 // this function rather than panicing through it, we need to
5570 // return them again, because they might have been changed by a
5571 // defer function. The runtime routines set the defer_stack
5572 // variable to true if we are returning from this function.
5574 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5575 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
5577 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
5579 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
5580 Bexpression
* bref
= ref
->get_backend(&context
);
5581 ret
= gogo
->backend()->conditional_expression(NULL
, bref
, ret
, NULL
,
5583 stmts
.push_back(gogo
->backend()->expression_statement(ret
));
5586 go_assert(*fini
== NULL
);
5587 *fini
= gogo
->backend()->statement_list(stmts
);
5590 // Return the statement that assigns values to this function's result struct.
5593 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
5594 Location location
) const
5596 const Typed_identifier_list
* results
= this->type_
->results();
5597 if (results
== NULL
|| results
->empty())
5600 go_assert(this->results_
!= NULL
);
5601 if (this->results_
->size() != results
->size())
5603 go_assert(saw_errors());
5604 return gogo
->backend()->error_statement();
5607 std::vector
<Bexpression
*> vals(results
->size());
5608 for (size_t i
= 0; i
< vals
.size(); ++i
)
5610 Named_object
* no
= (*this->results_
)[i
];
5611 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
5612 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
5613 if (no
->result_var_value()->is_in_heap())
5615 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
5616 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
5620 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
5625 Block::Block(Block
* enclosing
, Location location
)
5626 : enclosing_(enclosing
), statements_(),
5627 bindings_(new Bindings(enclosing
== NULL
5629 : enclosing
->bindings())),
5630 start_location_(location
),
5631 end_location_(UNKNOWN_LOCATION
)
5635 // Add a statement to a block.
5638 Block::add_statement(Statement
* statement
)
5640 this->statements_
.push_back(statement
);
5643 // Add a statement to the front of a block. This is slow but is only
5644 // used for reference counts of parameters.
5647 Block::add_statement_at_front(Statement
* statement
)
5649 this->statements_
.insert(this->statements_
.begin(), statement
);
5652 // Replace a statement in a block.
5655 Block::replace_statement(size_t index
, Statement
* s
)
5657 go_assert(index
< this->statements_
.size());
5658 this->statements_
[index
] = s
;
5661 // Add a statement before another statement.
5664 Block::insert_statement_before(size_t index
, Statement
* s
)
5666 go_assert(index
< this->statements_
.size());
5667 this->statements_
.insert(this->statements_
.begin() + index
, s
);
5670 // Add a statement after another statement.
5673 Block::insert_statement_after(size_t index
, Statement
* s
)
5675 go_assert(index
< this->statements_
.size());
5676 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
5679 // Traverse the tree.
5682 Block::traverse(Traverse
* traverse
)
5684 unsigned int traverse_mask
= traverse
->traverse_mask();
5686 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
5688 int t
= traverse
->block(this);
5689 if (t
== TRAVERSE_EXIT
)
5690 return TRAVERSE_EXIT
;
5691 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
5692 return TRAVERSE_CONTINUE
;
5696 & (Traverse::traverse_variables
5697 | Traverse::traverse_constants
5698 | Traverse::traverse_expressions
5699 | Traverse::traverse_types
)) != 0)
5701 const unsigned int e_or_t
= (Traverse::traverse_expressions
5702 | Traverse::traverse_types
);
5703 const unsigned int e_or_t_or_s
= (e_or_t
5704 | Traverse::traverse_statements
);
5705 for (Bindings::const_definitions_iterator pb
=
5706 this->bindings_
->begin_definitions();
5707 pb
!= this->bindings_
->end_definitions();
5710 int t
= TRAVERSE_CONTINUE
;
5711 switch ((*pb
)->classification())
5713 case Named_object::NAMED_OBJECT_CONST
:
5714 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
5715 t
= traverse
->constant(*pb
, false);
5716 if (t
== TRAVERSE_CONTINUE
5717 && (traverse_mask
& e_or_t
) != 0)
5719 Type
* tc
= (*pb
)->const_value()->type();
5721 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
5722 return TRAVERSE_EXIT
;
5723 t
= (*pb
)->const_value()->traverse_expression(traverse
);
5727 case Named_object::NAMED_OBJECT_VAR
:
5728 case Named_object::NAMED_OBJECT_RESULT_VAR
:
5729 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
5730 t
= traverse
->variable(*pb
);
5731 if (t
== TRAVERSE_CONTINUE
5732 && (traverse_mask
& e_or_t
) != 0)
5734 if ((*pb
)->is_result_variable()
5735 || (*pb
)->var_value()->has_type())
5737 Type
* tv
= ((*pb
)->is_variable()
5738 ? (*pb
)->var_value()->type()
5739 : (*pb
)->result_var_value()->type());
5741 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
5742 return TRAVERSE_EXIT
;
5745 if (t
== TRAVERSE_CONTINUE
5746 && (traverse_mask
& e_or_t_or_s
) != 0
5747 && (*pb
)->is_variable())
5748 t
= (*pb
)->var_value()->traverse_expression(traverse
,
5752 case Named_object::NAMED_OBJECT_FUNC
:
5753 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
5756 case Named_object::NAMED_OBJECT_TYPE
:
5757 if ((traverse_mask
& e_or_t
) != 0)
5758 t
= Type::traverse((*pb
)->type_value(), traverse
);
5761 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
5762 case Named_object::NAMED_OBJECT_UNKNOWN
:
5763 case Named_object::NAMED_OBJECT_ERRONEOUS
:
5766 case Named_object::NAMED_OBJECT_PACKAGE
:
5767 case Named_object::NAMED_OBJECT_SINK
:
5774 if (t
== TRAVERSE_EXIT
)
5775 return TRAVERSE_EXIT
;
5779 // No point in checking traverse_mask here--if we got here we always
5780 // want to walk the statements. The traversal can insert new
5781 // statements before or after the current statement. Inserting
5782 // statements before the current statement requires updating I via
5783 // the pointer; those statements will not be traversed. Any new
5784 // statements inserted after the current statement will be traversed
5786 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
5788 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
5789 return TRAVERSE_EXIT
;
5792 return TRAVERSE_CONTINUE
;
5795 // Work out types for unspecified variables and constants.
5798 Block::determine_types()
5800 for (Bindings::const_definitions_iterator pb
=
5801 this->bindings_
->begin_definitions();
5802 pb
!= this->bindings_
->end_definitions();
5805 if ((*pb
)->is_variable())
5806 (*pb
)->var_value()->determine_type();
5807 else if ((*pb
)->is_const())
5808 (*pb
)->const_value()->determine_type();
5811 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
5812 ps
!= this->statements_
.end();
5814 (*ps
)->determine_types();
5817 // Return true if the statements in this block may fall through.
5820 Block::may_fall_through() const
5822 if (this->statements_
.empty())
5824 return this->statements_
.back()->may_fall_through();
5827 // Convert a block to the backend representation.
5830 Block::get_backend(Translate_context
* context
)
5832 Gogo
* gogo
= context
->gogo();
5833 Named_object
* function
= context
->function();
5834 std::vector
<Bvariable
*> vars
;
5835 vars
.reserve(this->bindings_
->size_definitions());
5836 for (Bindings::const_definitions_iterator pv
=
5837 this->bindings_
->begin_definitions();
5838 pv
!= this->bindings_
->end_definitions();
5841 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
5842 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
5845 go_assert(function
!= NULL
);
5846 Bfunction
* bfunction
=
5847 function
->func_value()->get_or_make_decl(gogo
, function
);
5848 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
5849 vars
, this->start_location_
,
5850 this->end_location_
);
5852 Translate_context
subcontext(gogo
, function
, this, ret
);
5853 std::vector
<Bstatement
*> bstatements
;
5854 bstatements
.reserve(this->statements_
.size());
5855 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
5856 p
!= this->statements_
.end();
5858 bstatements
.push_back((*p
)->get_backend(&subcontext
));
5860 context
->backend()->block_add_statements(ret
, bstatements
);
5865 // Class Bindings_snapshot.
5867 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
5868 : block_(b
), counts_(), location_(location
)
5872 this->counts_
.push_back(b
->bindings()->size_definitions());
5877 // Report errors appropriate for a goto from B to this.
5880 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
5883 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
5885 this->check_goto_defs(loc
, this->block_
,
5886 this->block_
->bindings()->size_definitions(),
5890 // Report errors appropriate for a goto from this to B.
5893 Bindings_snapshot::check_goto_to(const Block
* b
)
5896 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
5898 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
5899 b
->bindings()->size_definitions());
5902 // Report errors appropriate for a goto at LOC from BFROM to BTO.
5903 // Return true if all is well, false if we reported an error. If this
5904 // returns true, it sets *PINDEX to the number of blocks BTO is above
5908 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
5909 const Block
* bto
, size_t* pindex
)
5911 // It is an error if BTO is not either BFROM or above BFROM.
5913 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
5917 error_at(loc
, "goto jumps into block");
5918 inform(bto
->start_location(), "goto target block starts here");
5926 // Report errors appropriate for a goto at LOC ending at BLOCK, where
5927 // CFROM is the number of names defined at the point of the goto and
5928 // CTO is the number of names defined at the point of the label.
5931 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
5932 size_t cfrom
, size_t cto
)
5936 Bindings::const_definitions_iterator p
=
5937 block
->bindings()->begin_definitions();
5938 for (size_t i
= 0; i
< cfrom
; ++i
)
5940 go_assert(p
!= block
->bindings()->end_definitions());
5943 go_assert(p
!= block
->bindings()->end_definitions());
5945 std::string n
= (*p
)->message_name();
5946 error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
5947 inform((*p
)->location(), "%qs defined here", n
.c_str());
5951 // Class Function_declaration.
5953 // Return the function descriptor.
5956 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
5958 go_assert(!this->fntype_
->is_method());
5959 if (this->descriptor_
== NULL
)
5960 this->descriptor_
= Expression::make_func_descriptor(no
);
5961 return this->descriptor_
;
5966 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
5967 bool is_parameter
, bool is_receiver
,
5969 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
5970 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
5971 is_closure_(false), is_receiver_(is_receiver
),
5972 is_varargs_parameter_(false), is_used_(false),
5973 is_address_taken_(false), is_non_escaping_address_taken_(false),
5974 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
5975 type_from_init_tuple_(false), type_from_range_index_(false),
5976 type_from_range_value_(false), type_from_chan_element_(false),
5977 is_type_switch_var_(false), determined_type_(false),
5978 in_unique_section_(false), escapes_(true)
5980 go_assert(type
!= NULL
|| init
!= NULL
);
5981 go_assert(!is_parameter
|| init
== NULL
);
5984 // Traverse the initializer expression.
5987 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
5989 if (this->preinit_
!= NULL
)
5991 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
5992 return TRAVERSE_EXIT
;
5994 if (this->init_
!= NULL
5996 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
5999 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
6000 return TRAVERSE_EXIT
;
6002 return TRAVERSE_CONTINUE
;
6005 // Lower the initialization expression after parsing is complete.
6008 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
6009 Statement_inserter
* inserter
)
6011 Named_object
* dep
= gogo
->var_depends_on(this);
6012 if (dep
!= NULL
&& dep
->is_variable())
6013 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
6015 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
6019 // We will give an error elsewhere, this is just to prevent
6020 // an infinite loop.
6025 Statement_inserter global_inserter
;
6026 if (this->is_global_
)
6028 global_inserter
= Statement_inserter(gogo
, this);
6029 inserter
= &global_inserter
;
6032 gogo
->lower_expression(function
, inserter
, &this->init_
);
6034 this->seen_
= false;
6036 this->init_is_lowered_
= true;
6040 // Flatten the initialization expression after ordering evaluations.
6043 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
6044 Statement_inserter
* inserter
)
6046 Named_object
* dep
= gogo
->var_depends_on(this);
6047 if (dep
!= NULL
&& dep
->is_variable())
6048 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
6050 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
6054 // We will give an error elsewhere, this is just to prevent
6055 // an infinite loop.
6060 Statement_inserter global_inserter
;
6061 if (this->is_global_
)
6063 global_inserter
= Statement_inserter(gogo
, this);
6064 inserter
= &global_inserter
;
6067 gogo
->flatten_expression(function
, inserter
, &this->init_
);
6069 // If an interface conversion is needed, we need a temporary
6071 if (this->type_
!= NULL
6072 && !Type::are_identical(this->type_
, this->init_
->type(), false,
6074 && this->init_
->type()->interface_type() != NULL
6075 && !this->init_
->is_variable())
6077 Temporary_statement
* temp
=
6078 Statement::make_temporary(NULL
, this->init_
, this->location_
);
6079 inserter
->insert(temp
);
6080 this->init_
= Expression::make_temporary_reference(temp
,
6084 this->seen_
= false;
6085 this->init_is_flattened_
= true;
6089 // Get the preinit block.
6092 Variable::preinit_block(Gogo
* gogo
)
6094 go_assert(this->is_global_
);
6095 if (this->preinit_
== NULL
)
6096 this->preinit_
= new Block(NULL
, this->location());
6098 // If a global variable has a preinitialization statement, then we
6099 // need to have an initialization function.
6100 gogo
->set_need_init_fn();
6102 return this->preinit_
;
6105 // Add a statement to be run before the initialization expression.
6108 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
6110 Block
* b
= this->preinit_block(gogo
);
6111 b
->add_statement(s
);
6112 b
->set_end_location(s
->location());
6115 // Whether this variable has a type.
6118 Variable::has_type() const
6120 if (this->type_
== NULL
)
6123 // A variable created in a type switch case nil does not actually
6124 // have a type yet. It will be changed to use the initializer's
6125 // type in determine_type.
6126 if (this->is_type_switch_var_
6127 && this->type_
->is_nil_constant_as_type())
6133 // In an assignment which sets a variable to a tuple of EXPR, return
6134 // the type of the first element of the tuple.
6137 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
6139 if (expr
->map_index_expression() != NULL
)
6141 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
6143 return Type::make_error_type();
6144 return mt
->val_type();
6146 else if (expr
->receive_expression() != NULL
)
6148 Expression
* channel
= expr
->receive_expression()->channel();
6149 Type
* channel_type
= channel
->type();
6150 if (channel_type
->channel_type() == NULL
)
6151 return Type::make_error_type();
6152 return channel_type
->channel_type()->element_type();
6157 error_at(this->location(), "invalid tuple definition");
6158 return Type::make_error_type();
6162 // Given EXPR used in a range clause, return either the index type or
6163 // the value type of the range, depending upon GET_INDEX_TYPE.
6166 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
6167 bool report_error
) const
6169 Type
* t
= expr
->type();
6170 if (t
->array_type() != NULL
6171 || (t
->points_to() != NULL
6172 && t
->points_to()->array_type() != NULL
6173 && !t
->points_to()->is_slice_type()))
6176 return Type::lookup_integer_type("int");
6178 return t
->deref()->array_type()->element_type();
6180 else if (t
->is_string_type())
6183 return Type::lookup_integer_type("int");
6185 return Type::lookup_integer_type("int32");
6187 else if (t
->map_type() != NULL
)
6190 return t
->map_type()->key_type();
6192 return t
->map_type()->val_type();
6194 else if (t
->channel_type() != NULL
)
6197 return t
->channel_type()->element_type();
6201 error_at(this->location(),
6202 "invalid definition of value variable for channel range");
6203 return Type::make_error_type();
6209 error_at(this->location(), "invalid type for range clause");
6210 return Type::make_error_type();
6214 // EXPR should be a channel. Return the channel's element type.
6217 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
6219 Type
* t
= expr
->type();
6220 if (t
->channel_type() != NULL
)
6221 return t
->channel_type()->element_type();
6225 error_at(this->location(), "expected channel");
6226 return Type::make_error_type();
6230 // Return the type of the Variable. This may be called before
6231 // Variable::determine_type is called, which means that we may need to
6232 // get the type from the initializer. FIXME: If we combine lowering
6233 // with type determination, then this should be unnecessary.
6238 // A variable in a type switch with a nil case will have the wrong
6239 // type here. This gets fixed up in determine_type, below.
6240 Type
* type
= this->type_
;
6241 Expression
* init
= this->init_
;
6242 if (this->is_type_switch_var_
6244 && this->type_
->is_nil_constant_as_type())
6246 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6247 go_assert(tge
!= NULL
);
6254 if (this->type_
== NULL
|| !this->type_
->is_error_type())
6256 error_at(this->location_
, "variable initializer refers to itself");
6257 this->type_
= Type::make_error_type();
6266 else if (this->type_from_init_tuple_
)
6267 type
= this->type_from_tuple(init
, false);
6268 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6269 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
6270 else if (this->type_from_chan_element_
)
6271 type
= this->type_from_chan_element(init
, false);
6274 go_assert(init
!= NULL
);
6275 type
= init
->type();
6276 go_assert(type
!= NULL
);
6278 // Variables should not have abstract types.
6279 if (type
->is_abstract())
6280 type
= type
->make_non_abstract_type();
6282 if (type
->is_void_type())
6283 type
= Type::make_error_type();
6286 this->seen_
= false;
6291 // Fetch the type from a const pointer, in which case it should have
6292 // been set already.
6295 Variable::type() const
6297 go_assert(this->type_
!= NULL
);
6301 // Set the type if necessary.
6304 Variable::determine_type()
6306 if (this->determined_type_
)
6308 this->determined_type_
= true;
6310 if (this->preinit_
!= NULL
)
6311 this->preinit_
->determine_types();
6313 // A variable in a type switch with a nil case will have the wrong
6314 // type here. It will have an initializer which is a type guard.
6315 // We want to initialize it to the value without the type guard, and
6316 // use the type of that value as well.
6317 if (this->is_type_switch_var_
6318 && this->type_
!= NULL
6319 && this->type_
->is_nil_constant_as_type())
6321 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6322 go_assert(tge
!= NULL
);
6324 this->init_
= tge
->expr();
6327 if (this->init_
== NULL
)
6328 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
6329 else if (this->type_from_init_tuple_
)
6331 Expression
*init
= this->init_
;
6332 init
->determine_type_no_context();
6333 this->type_
= this->type_from_tuple(init
, true);
6336 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6338 Expression
* init
= this->init_
;
6339 init
->determine_type_no_context();
6340 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
6344 else if (this->type_from_chan_element_
)
6346 Expression
* init
= this->init_
;
6347 init
->determine_type_no_context();
6348 this->type_
= this->type_from_chan_element(init
, true);
6353 Type_context
context(this->type_
, false);
6354 this->init_
->determine_type(&context
);
6355 if (this->type_
== NULL
)
6357 Type
* type
= this->init_
->type();
6358 go_assert(type
!= NULL
);
6359 if (type
->is_abstract())
6360 type
= type
->make_non_abstract_type();
6362 if (type
->is_void_type())
6364 error_at(this->location_
, "variable has no type");
6365 type
= Type::make_error_type();
6367 else if (type
->is_nil_type())
6369 error_at(this->location_
, "variable defined to nil type");
6370 type
= Type::make_error_type();
6372 else if (type
->is_call_multiple_result_type())
6374 error_at(this->location_
,
6375 "single variable set to multiple-value function call");
6376 type
= Type::make_error_type();
6384 // Get the initial value of a variable. This does not
6385 // consider whether the variable is in the heap--it returns the
6386 // initial value as though it were always stored in the stack.
6389 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
6391 go_assert(this->preinit_
== NULL
);
6392 Location loc
= this->location();
6393 if (this->init_
== NULL
)
6395 go_assert(!this->is_parameter_
);
6396 if (this->is_global_
|| this->is_in_heap())
6398 Btype
* btype
= this->type()->get_backend(gogo
);
6399 return gogo
->backend()->zero_expression(btype
);
6403 Translate_context
context(gogo
, function
, NULL
, NULL
);
6404 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
6405 return init
->get_backend(&context
);
6409 // Get the initial value of a variable when a block is required.
6410 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6413 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
6414 Bvariable
* var_decl
)
6416 go_assert(this->preinit_
!= NULL
);
6418 // We want to add the variable assignment to the end of the preinit
6421 Translate_context
context(gogo
, function
, NULL
, NULL
);
6422 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
6424 // It's possible to have pre-init statements without an initializer
6425 // if the pre-init statements set the variable.
6426 Bstatement
* decl_init
= NULL
;
6427 if (this->init_
!= NULL
)
6429 if (var_decl
== NULL
)
6431 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
6432 decl_init
= gogo
->backend()->expression_statement(init_bexpr
);
6436 Location loc
= this->location();
6437 Expression
* val_expr
=
6438 Expression::make_cast(this->type(), this->init_
, loc
);
6439 Bexpression
* val
= val_expr
->get_backend(&context
);
6440 Bexpression
* var_ref
= gogo
->backend()->var_expression(var_decl
, loc
);
6441 decl_init
= gogo
->backend()->assignment_statement(var_ref
, val
, loc
);
6444 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
6445 if (decl_init
!= NULL
)
6446 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
6450 // Export the variable
6453 Variable::export_var(Export
* exp
, const std::string
& name
) const
6455 go_assert(this->is_global_
);
6456 exp
->write_c_string("var ");
6457 exp
->write_string(name
);
6458 exp
->write_c_string(" ");
6459 exp
->write_type(this->type());
6460 exp
->write_c_string(";\n");
6463 // Import a variable.
6466 Variable::import_var(Import
* imp
, std::string
* pname
, Type
** ptype
)
6468 imp
->require_c_string("var ");
6469 *pname
= imp
->read_identifier();
6470 imp
->require_c_string(" ");
6471 *ptype
= imp
->read_type();
6472 imp
->require_c_string(";\n");
6475 // Convert a variable to the backend representation.
6478 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6479 const Package
* package
, const std::string
& name
)
6481 if (this->backend_
== NULL
)
6483 Backend
* backend
= gogo
->backend();
6484 Type
* type
= this->type_
;
6485 if (type
->is_error_type()
6486 || (type
->is_undefined()
6487 && (!this->is_global_
|| package
== NULL
)))
6488 this->backend_
= backend
->error_variable();
6491 bool is_parameter
= this->is_parameter_
;
6492 if (this->is_receiver_
&& type
->points_to() == NULL
)
6493 is_parameter
= false;
6494 if (this->is_in_heap())
6496 is_parameter
= false;
6497 type
= Type::make_pointer_type(type
);
6500 std::string n
= Gogo::unpack_hidden_name(name
);
6501 Btype
* btype
= type
->get_backend(gogo
);
6504 if (gogo
->is_zero_value(this))
6505 bvar
= gogo
->backend_zero_value();
6506 else if (this->is_global_
)
6507 bvar
= backend
->global_variable((package
== NULL
6508 ? gogo
->package_name()
6509 : package
->package_name()),
6511 ? gogo
->pkgpath_symbol()
6512 : package
->pkgpath_symbol()),
6516 Gogo::is_hidden_name(name
),
6517 this->in_unique_section_
,
6519 else if (function
== NULL
)
6521 go_assert(saw_errors());
6522 bvar
= backend
->error_variable();
6526 Bfunction
* bfunction
= function
->func_value()->get_decl();
6527 bool is_address_taken
= (this->is_non_escaping_address_taken_
6528 && !this->is_in_heap());
6529 if (this->is_closure())
6530 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
6532 else if (is_parameter
)
6533 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
6537 bvar
= backend
->local_variable(bfunction
, n
, btype
,
6541 this->backend_
= bvar
;
6544 return this->backend_
;
6547 // Class Result_variable.
6549 // Convert a result variable to the backend representation.
6552 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6553 const std::string
& name
)
6555 if (this->backend_
== NULL
)
6557 Backend
* backend
= gogo
->backend();
6558 Type
* type
= this->type_
;
6559 if (type
->is_error())
6560 this->backend_
= backend
->error_variable();
6563 if (this->is_in_heap())
6564 type
= Type::make_pointer_type(type
);
6565 Btype
* btype
= type
->get_backend(gogo
);
6566 Bfunction
* bfunction
= function
->func_value()->get_decl();
6567 std::string n
= Gogo::unpack_hidden_name(name
);
6568 bool is_address_taken
= (this->is_non_escaping_address_taken_
6569 && !this->is_in_heap());
6570 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
6575 return this->backend_
;
6578 // Class Named_constant.
6580 // Traverse the initializer expression.
6583 Named_constant::traverse_expression(Traverse
* traverse
)
6585 return Expression::traverse(&this->expr_
, traverse
);
6588 // Determine the type of the constant.
6591 Named_constant::determine_type()
6593 if (this->type_
!= NULL
)
6595 Type_context
context(this->type_
, false);
6596 this->expr_
->determine_type(&context
);
6600 // A constant may have an abstract type.
6601 Type_context
context(NULL
, true);
6602 this->expr_
->determine_type(&context
);
6603 this->type_
= this->expr_
->type();
6604 go_assert(this->type_
!= NULL
);
6608 // Indicate that we found and reported an error for this constant.
6611 Named_constant::set_error()
6613 this->type_
= Type::make_error_type();
6614 this->expr_
= Expression::make_error(this->location_
);
6617 // Export a constant.
6620 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
6622 exp
->write_c_string("const ");
6623 exp
->write_string(name
);
6624 exp
->write_c_string(" ");
6625 if (!this->type_
->is_abstract())
6627 exp
->write_type(this->type_
);
6628 exp
->write_c_string(" ");
6630 exp
->write_c_string("= ");
6631 this->expr()->export_expression(exp
);
6632 exp
->write_c_string(";\n");
6635 // Import a constant.
6638 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
6641 imp
->require_c_string("const ");
6642 *pname
= imp
->read_identifier();
6643 imp
->require_c_string(" ");
6644 if (imp
->peek_char() == '=')
6648 *ptype
= imp
->read_type();
6649 imp
->require_c_string(" ");
6651 imp
->require_c_string("= ");
6652 *pexpr
= Expression::import_expression(imp
);
6653 imp
->require_c_string(";\n");
6656 // Get the backend representation.
6659 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
6661 if (this->bconst_
== NULL
)
6663 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
6664 Type
* type
= this->type();
6665 Location loc
= this->location();
6667 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
6668 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
6669 if (type
!= NULL
&& type
->is_numeric_type())
6671 Btype
* btype
= type
->get_backend(gogo
);
6672 std::string name
= const_no
->get_id(gogo
);
6674 gogo
->backend()->named_constant_expression(btype
, name
,
6677 this->bconst_
= const_decl
;
6679 return this->bconst_
;
6685 Type_declaration::add_method(const std::string
& name
, Function
* function
)
6687 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
6688 this->methods_
.push_back(ret
);
6692 // Add a method declaration.
6695 Type_declaration::add_method_declaration(const std::string
& name
,
6697 Function_type
* type
,
6700 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
6702 this->methods_
.push_back(ret
);
6706 // Return whether any methods ere defined.
6709 Type_declaration::has_methods() const
6711 return !this->methods_
.empty();
6714 // Define methods for the real type.
6717 Type_declaration::define_methods(Named_type
* nt
)
6719 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
6720 p
!= this->methods_
.end();
6722 nt
->add_existing_method(*p
);
6725 // We are using the type. Return true if we should issue a warning.
6728 Type_declaration::using_type()
6730 bool ret
= !this->issued_warning_
;
6731 this->issued_warning_
= true;
6735 // Class Unknown_name.
6737 // Set the real named object.
6740 Unknown_name::set_real_named_object(Named_object
* no
)
6742 go_assert(this->real_named_object_
== NULL
);
6743 go_assert(!no
->is_unknown());
6744 this->real_named_object_
= no
;
6747 // Class Named_object.
6749 Named_object::Named_object(const std::string
& name
,
6750 const Package
* package
,
6751 Classification classification
)
6752 : name_(name
), package_(package
), classification_(classification
)
6754 if (Gogo::is_sink_name(name
))
6755 go_assert(classification
== NAMED_OBJECT_SINK
);
6758 // Make an unknown name. This is used by the parser. The name must
6759 // be resolved later. Unknown names are only added in the current
6763 Named_object::make_unknown_name(const std::string
& name
,
6766 Named_object
* named_object
= new Named_object(name
, NULL
,
6767 NAMED_OBJECT_UNKNOWN
);
6768 Unknown_name
* value
= new Unknown_name(location
);
6769 named_object
->u_
.unknown_value
= value
;
6770 return named_object
;
6776 Named_object::make_constant(const Typed_identifier
& tid
,
6777 const Package
* package
, Expression
* expr
,
6780 Named_object
* named_object
= new Named_object(tid
.name(), package
,
6781 NAMED_OBJECT_CONST
);
6782 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
6785 named_object
->u_
.const_value
= named_constant
;
6786 return named_object
;
6789 // Make a named type.
6792 Named_object::make_type(const std::string
& name
, const Package
* package
,
6793 Type
* type
, Location location
)
6795 Named_object
* named_object
= new Named_object(name
, package
,
6797 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
6798 named_object
->u_
.type_value
= named_type
;
6799 return named_object
;
6802 // Make a type declaration.
6805 Named_object::make_type_declaration(const std::string
& name
,
6806 const Package
* package
,
6809 Named_object
* named_object
= new Named_object(name
, package
,
6810 NAMED_OBJECT_TYPE_DECLARATION
);
6811 Type_declaration
* type_declaration
= new Type_declaration(location
);
6812 named_object
->u_
.type_declaration
= type_declaration
;
6813 return named_object
;
6819 Named_object::make_variable(const std::string
& name
, const Package
* package
,
6822 Named_object
* named_object
= new Named_object(name
, package
,
6824 named_object
->u_
.var_value
= variable
;
6825 return named_object
;
6828 // Make a result variable.
6831 Named_object::make_result_variable(const std::string
& name
,
6832 Result_variable
* result
)
6834 Named_object
* named_object
= new Named_object(name
, NULL
,
6835 NAMED_OBJECT_RESULT_VAR
);
6836 named_object
->u_
.result_var_value
= result
;
6837 return named_object
;
6840 // Make a sink. This is used for the special blank identifier _.
6843 Named_object::make_sink()
6845 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
6848 // Make a named function.
6851 Named_object::make_function(const std::string
& name
, const Package
* package
,
6854 Named_object
* named_object
= new Named_object(name
, package
,
6856 named_object
->u_
.func_value
= function
;
6857 return named_object
;
6860 // Make a function declaration.
6863 Named_object::make_function_declaration(const std::string
& name
,
6864 const Package
* package
,
6865 Function_type
* fntype
,
6868 Named_object
* named_object
= new Named_object(name
, package
,
6869 NAMED_OBJECT_FUNC_DECLARATION
);
6870 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
6871 named_object
->u_
.func_declaration_value
= func_decl
;
6872 return named_object
;
6878 Named_object::make_package(const std::string
& alias
, Package
* package
)
6880 Named_object
* named_object
= new Named_object(alias
, NULL
,
6881 NAMED_OBJECT_PACKAGE
);
6882 named_object
->u_
.package_value
= package
;
6883 return named_object
;
6886 // Return the name to use in an error message.
6889 Named_object::message_name() const
6891 if (this->package_
== NULL
)
6892 return Gogo::message_name(this->name_
);
6894 if (this->package_
->has_package_name())
6895 ret
= this->package_
->package_name();
6897 ret
= this->package_
->pkgpath();
6898 ret
= Gogo::message_name(ret
);
6900 ret
+= Gogo::message_name(this->name_
);
6904 // Set the type when a declaration is defined.
6907 Named_object::set_type_value(Named_type
* named_type
)
6909 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
6910 Type_declaration
* td
= this->u_
.type_declaration
;
6911 td
->define_methods(named_type
);
6913 Named_object
* in_function
= td
->in_function(&index
);
6914 if (in_function
!= NULL
)
6915 named_type
->set_in_function(in_function
, index
);
6917 this->classification_
= NAMED_OBJECT_TYPE
;
6918 this->u_
.type_value
= named_type
;
6921 // Define a function which was previously declared.
6924 Named_object::set_function_value(Function
* function
)
6926 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
6927 if (this->func_declaration_value()->has_descriptor())
6929 Expression
* descriptor
=
6930 this->func_declaration_value()->descriptor(NULL
, NULL
);
6931 function
->set_descriptor(descriptor
);
6933 this->classification_
= NAMED_OBJECT_FUNC
;
6934 // FIXME: We should free the old value.
6935 this->u_
.func_value
= function
;
6938 // Declare an unknown object as a type declaration.
6941 Named_object::declare_as_type()
6943 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
6944 Unknown_name
* unk
= this->u_
.unknown_value
;
6945 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
6946 this->u_
.type_declaration
= new Type_declaration(unk
->location());
6950 // Return the location of a named object.
6953 Named_object::location() const
6955 switch (this->classification_
)
6958 case NAMED_OBJECT_UNINITIALIZED
:
6961 case NAMED_OBJECT_ERRONEOUS
:
6962 return Linemap::unknown_location();
6964 case NAMED_OBJECT_UNKNOWN
:
6965 return this->unknown_value()->location();
6967 case NAMED_OBJECT_CONST
:
6968 return this->const_value()->location();
6970 case NAMED_OBJECT_TYPE
:
6971 return this->type_value()->location();
6973 case NAMED_OBJECT_TYPE_DECLARATION
:
6974 return this->type_declaration_value()->location();
6976 case NAMED_OBJECT_VAR
:
6977 return this->var_value()->location();
6979 case NAMED_OBJECT_RESULT_VAR
:
6980 return this->result_var_value()->location();
6982 case NAMED_OBJECT_SINK
:
6985 case NAMED_OBJECT_FUNC
:
6986 return this->func_value()->location();
6988 case NAMED_OBJECT_FUNC_DECLARATION
:
6989 return this->func_declaration_value()->location();
6991 case NAMED_OBJECT_PACKAGE
:
6992 return this->package_value()->location();
6996 // Export a named object.
6999 Named_object::export_named_object(Export
* exp
) const
7001 switch (this->classification_
)
7004 case NAMED_OBJECT_UNINITIALIZED
:
7005 case NAMED_OBJECT_UNKNOWN
:
7008 case NAMED_OBJECT_ERRONEOUS
:
7011 case NAMED_OBJECT_CONST
:
7012 this->const_value()->export_const(exp
, this->name_
);
7015 case NAMED_OBJECT_TYPE
:
7016 this->type_value()->export_named_type(exp
, this->name_
);
7019 case NAMED_OBJECT_TYPE_DECLARATION
:
7020 error_at(this->type_declaration_value()->location(),
7021 "attempt to export %<%s%> which was declared but not defined",
7022 this->message_name().c_str());
7025 case NAMED_OBJECT_FUNC_DECLARATION
:
7026 this->func_declaration_value()->export_func(exp
, this->name_
);
7029 case NAMED_OBJECT_VAR
:
7030 this->var_value()->export_var(exp
, this->name_
);
7033 case NAMED_OBJECT_RESULT_VAR
:
7034 case NAMED_OBJECT_SINK
:
7037 case NAMED_OBJECT_FUNC
:
7038 this->func_value()->export_func(exp
, this->name_
);
7043 // Convert a variable to the backend representation.
7046 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
7048 if (this->classification_
== NAMED_OBJECT_VAR
)
7049 return this->var_value()->get_backend_variable(gogo
, function
,
7050 this->package_
, this->name_
);
7051 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
7052 return this->result_var_value()->get_backend_variable(gogo
, function
,
7059 // Return the external identifier for this object.
7062 Named_object::get_id(Gogo
* gogo
)
7064 go_assert(!this->is_variable() && !this->is_result_variable());
7065 std::string decl_name
;
7066 if (this->is_function_declaration()
7067 && !this->func_declaration_value()->asm_name().empty())
7068 decl_name
= this->func_declaration_value()->asm_name();
7069 else if (this->is_type()
7070 && Linemap::is_predeclared_location(this->type_value()->location()))
7072 // We don't need the package name for builtin types.
7073 decl_name
= Gogo::unpack_hidden_name(this->name_
);
7077 std::string package_name
;
7078 if (this->package_
== NULL
)
7079 package_name
= gogo
->package_name();
7081 package_name
= this->package_
->package_name();
7083 // Note that this will be misleading if this is an unexported
7084 // method generated for an embedded imported type. In that case
7085 // the unexported method should have the package name of the
7086 // package from which it is imported, but we are going to give
7087 // it our package name. Fixing this would require knowing the
7088 // package name, but we only know the package path. It might be
7089 // better to use package paths here anyhow. This doesn't affect
7090 // the assembler code, because we always set that name in
7091 // Function::get_or_make_decl anyhow. FIXME.
7093 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
7095 Function_type
* fntype
;
7096 if (this->is_function())
7097 fntype
= this->func_value()->type();
7098 else if (this->is_function_declaration())
7099 fntype
= this->func_declaration_value()->type();
7102 if (fntype
!= NULL
&& fntype
->is_method())
7104 decl_name
.push_back('.');
7105 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
7108 if (this->is_type())
7111 const Named_object
* in_function
= this->type_value()->in_function(&index
);
7112 if (in_function
!= NULL
)
7114 decl_name
+= '$' + Gogo::unpack_hidden_name(in_function
->name());
7118 snprintf(buf
, sizeof buf
, "%u", index
);
7127 // Get the backend representation for this named object.
7130 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
7131 std::vector
<Btype
*>& type_decls
,
7132 std::vector
<Bfunction
*>& func_decls
)
7134 switch (this->classification_
)
7136 case NAMED_OBJECT_CONST
:
7137 if (!Gogo::is_erroneous_name(this->name_
))
7138 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
7141 case NAMED_OBJECT_TYPE
:
7143 Named_type
* named_type
= this->u_
.type_value
;
7144 if (!Gogo::is_erroneous_name(this->name_
))
7145 type_decls
.push_back(named_type
->get_backend(gogo
));
7147 // We need to produce a type descriptor for every named
7148 // type, and for a pointer to every named type, since
7149 // other files or packages might refer to them. We need
7150 // to do this even for hidden types, because they might
7151 // still be returned by some function. Simply calling the
7152 // type_descriptor method is enough to create the type
7153 // descriptor, even though we don't do anything with it.
7154 if (this->package_
== NULL
)
7157 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7158 named_type
->gc_symbol_pointer(gogo
);
7159 Type
* pn
= Type::make_pointer_type(named_type
);
7160 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7161 pn
->gc_symbol_pointer(gogo
);
7166 case NAMED_OBJECT_TYPE_DECLARATION
:
7167 error("reference to undefined type %qs",
7168 this->message_name().c_str());
7171 case NAMED_OBJECT_VAR
:
7172 case NAMED_OBJECT_RESULT_VAR
:
7173 case NAMED_OBJECT_SINK
:
7176 case NAMED_OBJECT_FUNC
:
7178 Function
* func
= this->u_
.func_value
;
7179 if (!Gogo::is_erroneous_name(this->name_
))
7180 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
7182 if (func
->block() != NULL
)
7183 func
->build(gogo
, this);
7187 case NAMED_OBJECT_ERRONEOUS
:
7197 Bindings::Bindings(Bindings
* enclosing
)
7198 : enclosing_(enclosing
), named_objects_(), bindings_()
7205 Bindings::clear_file_scope(Gogo
* gogo
)
7207 Contour::iterator p
= this->bindings_
.begin();
7208 while (p
!= this->bindings_
.end())
7211 if (p
->second
->package() != NULL
)
7213 else if (p
->second
->is_package())
7215 else if (p
->second
->is_function()
7216 && !p
->second
->func_value()->type()->is_method()
7217 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
7226 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
7227 p
= this->bindings_
.erase(p
);
7232 // Look up a symbol.
7235 Bindings::lookup(const std::string
& name
) const
7237 Contour::const_iterator p
= this->bindings_
.find(name
);
7238 if (p
!= this->bindings_
.end())
7239 return p
->second
->resolve();
7240 else if (this->enclosing_
!= NULL
)
7241 return this->enclosing_
->lookup(name
);
7246 // Look up a symbol locally.
7249 Bindings::lookup_local(const std::string
& name
) const
7251 Contour::const_iterator p
= this->bindings_
.find(name
);
7252 if (p
== this->bindings_
.end())
7257 // Remove an object from a set of bindings. This is used for a
7258 // special case in thunks for functions which call recover.
7261 Bindings::remove_binding(Named_object
* no
)
7263 Contour::iterator pb
= this->bindings_
.find(no
->name());
7264 go_assert(pb
!= this->bindings_
.end());
7265 this->bindings_
.erase(pb
);
7266 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
7267 pn
!= this->named_objects_
.end();
7272 this->named_objects_
.erase(pn
);
7279 // Add a method to the list of objects. This is not added to the
7280 // lookup table. This is so that we have a single list of objects
7281 // declared at the top level, which we walk through when it's time to
7282 // convert to trees.
7285 Bindings::add_method(Named_object
* method
)
7287 this->named_objects_
.push_back(method
);
7290 // Add a generic Named_object to a Contour.
7293 Bindings::add_named_object_to_contour(Contour
* contour
,
7294 Named_object
* named_object
)
7296 go_assert(named_object
== named_object
->resolve());
7297 const std::string
& name(named_object
->name());
7298 go_assert(!Gogo::is_sink_name(name
));
7300 std::pair
<Contour::iterator
, bool> ins
=
7301 contour
->insert(std::make_pair(name
, named_object
));
7304 // The name was already there.
7305 if (named_object
->package() != NULL
7306 && ins
.first
->second
->package() == named_object
->package()
7307 && (ins
.first
->second
->classification()
7308 == named_object
->classification()))
7310 // This is a second import of the same object.
7311 return ins
.first
->second
;
7313 ins
.first
->second
= this->new_definition(ins
.first
->second
,
7315 return ins
.first
->second
;
7319 // Don't push declarations on the list. We push them on when
7320 // and if we find the definitions. That way we genericize the
7321 // functions in order.
7322 if (!named_object
->is_type_declaration()
7323 && !named_object
->is_function_declaration()
7324 && !named_object
->is_unknown())
7325 this->named_objects_
.push_back(named_object
);
7326 return named_object
;
7330 // We had an existing named object OLD_OBJECT, and we've seen a new
7331 // one NEW_OBJECT with the same name. FIXME: This does not free the
7332 // new object when we don't need it.
7335 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
7337 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
7341 switch (old_object
->classification())
7344 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
7347 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7350 case Named_object::NAMED_OBJECT_UNKNOWN
:
7352 Named_object
* real
= old_object
->unknown_value()->real_named_object();
7354 return this->new_definition(real
, new_object
);
7355 go_assert(!new_object
->is_unknown());
7356 old_object
->unknown_value()->set_real_named_object(new_object
);
7357 if (!new_object
->is_type_declaration()
7358 && !new_object
->is_function_declaration())
7359 this->named_objects_
.push_back(new_object
);
7363 case Named_object::NAMED_OBJECT_CONST
:
7366 case Named_object::NAMED_OBJECT_TYPE
:
7367 if (new_object
->is_type_declaration())
7371 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7372 if (new_object
->is_type_declaration())
7374 if (new_object
->is_type())
7376 old_object
->set_type_value(new_object
->type_value());
7377 new_object
->type_value()->set_named_object(old_object
);
7378 this->named_objects_
.push_back(old_object
);
7383 case Named_object::NAMED_OBJECT_VAR
:
7384 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7385 // We have already given an error in the parser for cases where
7386 // one parameter or result variable redeclares another one.
7387 if ((new_object
->is_variable()
7388 && new_object
->var_value()->is_parameter())
7389 || new_object
->is_result_variable())
7393 case Named_object::NAMED_OBJECT_SINK
:
7396 case Named_object::NAMED_OBJECT_FUNC
:
7397 if (new_object
->is_function_declaration())
7399 if (!new_object
->func_declaration_value()->asm_name().empty())
7400 sorry("__asm__ for function definitions");
7401 Function_type
* old_type
= old_object
->func_value()->type();
7402 Function_type
* new_type
=
7403 new_object
->func_declaration_value()->type();
7404 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7409 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7411 Function_type
* old_type
= old_object
->func_declaration_value()->type();
7412 if (new_object
->is_function_declaration())
7414 Function_type
* new_type
=
7415 new_object
->func_declaration_value()->type();
7416 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7419 if (new_object
->is_function())
7421 Function_type
* new_type
= new_object
->func_value()->type();
7422 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7424 if (!old_object
->func_declaration_value()->asm_name().empty())
7425 sorry("__asm__ for function definitions");
7426 old_object
->set_function_value(new_object
->func_value());
7427 this->named_objects_
.push_back(old_object
);
7434 case Named_object::NAMED_OBJECT_PACKAGE
:
7438 std::string n
= old_object
->message_name();
7440 error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
7442 error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
7445 inform(old_object
->location(), "previous definition of %qs was here",
7451 // Add a named type.
7454 Bindings::add_named_type(Named_type
* named_type
)
7456 return this->add_named_object(named_type
->named_object());
7462 Bindings::add_function(const std::string
& name
, const Package
* package
,
7465 return this->add_named_object(Named_object::make_function(name
, package
,
7469 // Add a function declaration.
7472 Bindings::add_function_declaration(const std::string
& name
,
7473 const Package
* package
,
7474 Function_type
* type
,
7477 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
7479 return this->add_named_object(no
);
7482 // Define a type which was previously declared.
7485 Bindings::define_type(Named_object
* no
, Named_type
* type
)
7487 no
->set_type_value(type
);
7488 this->named_objects_
.push_back(no
);
7491 // Mark all local variables as used. This is used for some types of
7495 Bindings::mark_locals_used()
7497 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
7498 p
!= this->named_objects_
.end();
7500 if ((*p
)->is_variable())
7501 (*p
)->var_value()->set_is_used();
7504 // Traverse bindings.
7507 Bindings::traverse(Traverse
* traverse
, bool is_global
)
7509 unsigned int traverse_mask
= traverse
->traverse_mask();
7511 // We don't use an iterator because we permit the traversal to add
7512 // new global objects.
7513 const unsigned int e_or_t
= (Traverse::traverse_expressions
7514 | Traverse::traverse_types
);
7515 const unsigned int e_or_t_or_s
= (e_or_t
7516 | Traverse::traverse_statements
);
7517 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
7519 Named_object
* p
= this->named_objects_
[i
];
7520 int t
= TRAVERSE_CONTINUE
;
7521 switch (p
->classification())
7523 case Named_object::NAMED_OBJECT_CONST
:
7524 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
7525 t
= traverse
->constant(p
, is_global
);
7526 if (t
== TRAVERSE_CONTINUE
7527 && (traverse_mask
& e_or_t
) != 0)
7529 Type
* tc
= p
->const_value()->type();
7531 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
7532 return TRAVERSE_EXIT
;
7533 t
= p
->const_value()->traverse_expression(traverse
);
7537 case Named_object::NAMED_OBJECT_VAR
:
7538 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7539 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
7540 t
= traverse
->variable(p
);
7541 if (t
== TRAVERSE_CONTINUE
7542 && (traverse_mask
& e_or_t
) != 0)
7544 if (p
->is_result_variable()
7545 || p
->var_value()->has_type())
7547 Type
* tv
= (p
->is_variable()
7548 ? p
->var_value()->type()
7549 : p
->result_var_value()->type());
7551 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
7552 return TRAVERSE_EXIT
;
7555 if (t
== TRAVERSE_CONTINUE
7556 && (traverse_mask
& e_or_t_or_s
) != 0
7557 && p
->is_variable())
7558 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
7561 case Named_object::NAMED_OBJECT_FUNC
:
7562 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
7563 t
= traverse
->function(p
);
7565 if (t
== TRAVERSE_CONTINUE
7567 & (Traverse::traverse_variables
7568 | Traverse::traverse_constants
7569 | Traverse::traverse_functions
7570 | Traverse::traverse_blocks
7571 | Traverse::traverse_statements
7572 | Traverse::traverse_expressions
7573 | Traverse::traverse_types
)) != 0)
7574 t
= p
->func_value()->traverse(traverse
);
7577 case Named_object::NAMED_OBJECT_PACKAGE
:
7578 // These are traversed in Gogo::traverse.
7579 go_assert(is_global
);
7582 case Named_object::NAMED_OBJECT_TYPE
:
7583 if ((traverse_mask
& e_or_t
) != 0)
7584 t
= Type::traverse(p
->type_value(), traverse
);
7587 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7588 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7589 case Named_object::NAMED_OBJECT_UNKNOWN
:
7590 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7593 case Named_object::NAMED_OBJECT_SINK
:
7598 if (t
== TRAVERSE_EXIT
)
7599 return TRAVERSE_EXIT
;
7602 // If we need to traverse types, check the function declarations,
7603 // which have types. Also check any methods of a type declaration.
7604 if ((traverse_mask
& e_or_t
) != 0)
7606 for (Bindings::const_declarations_iterator p
=
7607 this->begin_declarations();
7608 p
!= this->end_declarations();
7611 if (p
->second
->is_function_declaration())
7613 if (Type::traverse(p
->second
->func_declaration_value()->type(),
7616 return TRAVERSE_EXIT
;
7618 else if (p
->second
->is_type_declaration())
7620 const std::vector
<Named_object
*>* methods
=
7621 p
->second
->type_declaration_value()->methods();
7622 for (std::vector
<Named_object
*>::const_iterator pm
=
7624 pm
!= methods
->end();
7627 Named_object
* no
= *pm
;
7629 if (no
->is_function())
7630 t
= no
->func_value()->type();
7631 else if (no
->is_function_declaration())
7632 t
= no
->func_declaration_value()->type();
7635 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
7636 return TRAVERSE_EXIT
;
7642 return TRAVERSE_CONTINUE
;
7647 // Clear any references to this label.
7652 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
7653 p
!= this->refs_
.end();
7656 this->refs_
.clear();
7659 // Get the backend representation for a label.
7662 Label::get_backend_label(Translate_context
* context
)
7664 if (this->blabel_
== NULL
)
7666 Function
* function
= context
->function()->func_value();
7667 Bfunction
* bfunction
= function
->get_decl();
7668 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
7671 return this->blabel_
;
7674 // Return an expression for the address of this label.
7677 Label::get_addr(Translate_context
* context
, Location location
)
7679 Blabel
* label
= this->get_backend_label(context
);
7680 return context
->backend()->label_address(label
, location
);
7683 // Return the dummy label that represents any instance of the blank label.
7686 Label::create_dummy_label()
7688 static Label
* dummy_label
;
7689 if (dummy_label
== NULL
)
7691 dummy_label
= new Label("_");
7692 dummy_label
->set_is_used();
7697 // Class Unnamed_label.
7699 // Get the backend representation for an unnamed label.
7702 Unnamed_label::get_blabel(Translate_context
* context
)
7704 if (this->blabel_
== NULL
)
7706 Function
* function
= context
->function()->func_value();
7707 Bfunction
* bfunction
= function
->get_decl();
7708 this->blabel_
= context
->backend()->label(bfunction
, "",
7711 return this->blabel_
;
7714 // Return a statement which defines this unnamed label.
7717 Unnamed_label::get_definition(Translate_context
* context
)
7719 Blabel
* blabel
= this->get_blabel(context
);
7720 return context
->backend()->label_definition_statement(blabel
);
7723 // Return a goto statement to this unnamed label.
7726 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
7728 Blabel
* blabel
= this->get_blabel(context
);
7729 return context
->backend()->goto_statement(blabel
, location
);
7734 Package::Package(const std::string
& pkgpath
,
7735 const std::string
& pkgpath_symbol
, Location location
)
7736 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
7737 package_name_(), bindings_(new Bindings(NULL
)), priority_(0),
7738 location_(location
), used_(false), is_imported_(false),
7739 uses_sink_alias_(false)
7741 go_assert(!pkgpath
.empty());
7745 // Set the package name.
7748 Package::set_package_name(const std::string
& package_name
, Location location
)
7750 go_assert(!package_name
.empty());
7751 if (this->package_name_
.empty())
7752 this->package_name_
= package_name
;
7753 else if (this->package_name_
!= package_name
)
7755 "saw two different packages with the same package path %s: %s, %s",
7756 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
7757 package_name
.c_str());
7760 // Return the pkgpath symbol, which is a prefix for symbols defined in
7764 Package::pkgpath_symbol() const
7766 if (this->pkgpath_symbol_
.empty())
7767 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
7768 return this->pkgpath_symbol_
;
7771 // Set the package path symbol.
7774 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
7776 go_assert(!pkgpath_symbol
.empty());
7777 if (this->pkgpath_symbol_
.empty())
7778 this->pkgpath_symbol_
= pkgpath_symbol
;
7780 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
7783 // Set the priority. We may see multiple priorities for an imported
7784 // package; we want to use the largest one.
7787 Package::set_priority(int priority
)
7789 if (priority
> this->priority_
)
7790 this->priority_
= priority
;
7793 // Forget a given usage. If forgetting this usage means this package becomes
7794 // unused, report that error.
7797 Package::forget_usage(Expression
* usage
) const
7799 if (this->fake_uses_
.empty())
7802 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
7803 go_assert(p
!= this->fake_uses_
.end());
7804 this->fake_uses_
.erase(p
);
7806 if (this->fake_uses_
.empty())
7807 error_at(this->location(), "imported and not used: %s",
7808 Gogo::message_name(this->package_name()).c_str());
7811 // Clear the used field for the next file. If the only usages of this package
7812 // are possibly fake, keep the fake usages for lowering.
7815 Package::clear_used()
7817 if (this->used_
> this->fake_uses_
.size())
7818 this->fake_uses_
.clear();
7823 // Determine types of constants. Everything else in a package
7824 // (variables, function declarations) should already have a fixed
7825 // type. Constants may have abstract types.
7828 Package::determine_types()
7830 Bindings
* bindings
= this->bindings_
;
7831 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
7832 p
!= bindings
->end_definitions();
7835 if ((*p
)->is_const())
7836 (*p
)->const_value()->determine_type();
7844 Traverse::~Traverse()
7846 if (this->types_seen_
!= NULL
)
7847 delete this->types_seen_
;
7848 if (this->expressions_seen_
!= NULL
)
7849 delete this->expressions_seen_
;
7852 // Record that we are looking at a type, and return true if we have
7856 Traverse::remember_type(const Type
* type
)
7858 if (type
->is_error_type())
7860 go_assert((this->traverse_mask() & traverse_types
) != 0
7861 || (this->traverse_mask() & traverse_expressions
) != 0);
7862 // We mostly only have to remember named types. But it turns out
7863 // that an interface type can refer to itself without using a name
7864 // by relying on interface inheritance, as in
7865 // type I interface { F() interface{I} }
7866 if (type
->classification() != Type::TYPE_NAMED
7867 && type
->classification() != Type::TYPE_INTERFACE
)
7869 if (this->types_seen_
== NULL
)
7870 this->types_seen_
= new Types_seen();
7871 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
7875 // Record that we are looking at an expression, and return true if we
7876 // have already seen it.
7879 Traverse::remember_expression(const Expression
* expression
)
7881 go_assert((this->traverse_mask() & traverse_types
) != 0
7882 || (this->traverse_mask() & traverse_expressions
) != 0);
7883 if (this->expressions_seen_
== NULL
)
7884 this->expressions_seen_
= new Expressions_seen();
7885 std::pair
<Expressions_seen::iterator
, bool> ins
=
7886 this->expressions_seen_
->insert(expression
);
7890 // The default versions of these functions should never be called: the
7891 // traversal mask indicates which functions may be called.
7894 Traverse::variable(Named_object
*)
7900 Traverse::constant(Named_object
*, bool)
7906 Traverse::function(Named_object
*)
7912 Traverse::block(Block
*)
7918 Traverse::statement(Block
*, size_t*, Statement
*)
7924 Traverse::expression(Expression
**)
7930 Traverse::type(Type
*)
7935 // Class Statement_inserter.
7938 Statement_inserter::insert(Statement
* s
)
7940 if (this->block_
!= NULL
)
7942 go_assert(this->pindex_
!= NULL
);
7943 this->block_
->insert_statement_before(*this->pindex_
, s
);
7946 else if (this->var_
!= NULL
)
7947 this->var_
->add_preinit_statement(this->gogo_
, s
);
7949 go_assert(saw_errors());