1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
11 #include "filenames.h"
15 #include "go-optimize.h"
18 #include "statements.h"
19 #include "expressions.h"
28 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
33 globals_(new Bindings(NULL
)),
36 imported_unsafe_(false),
37 current_file_imported_unsafe_(false),
48 pkgpath_from_option_(false),
49 prefix_from_option_(false),
50 relative_import_path_(),
53 specific_type_functions_(),
54 specific_type_functions_are_written_(false),
55 named_types_are_converted_(false)
57 const Location loc
= Linemap::predeclared_location();
59 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
60 RUNTIME_TYPE_KIND_UINT8
);
61 this->add_named_type(uint8_type
);
62 this->add_named_type(Type::make_integer_type("uint16", true, 16,
63 RUNTIME_TYPE_KIND_UINT16
));
64 this->add_named_type(Type::make_integer_type("uint32", true, 32,
65 RUNTIME_TYPE_KIND_UINT32
));
66 this->add_named_type(Type::make_integer_type("uint64", true, 64,
67 RUNTIME_TYPE_KIND_UINT64
));
69 this->add_named_type(Type::make_integer_type("int8", false, 8,
70 RUNTIME_TYPE_KIND_INT8
));
71 this->add_named_type(Type::make_integer_type("int16", false, 16,
72 RUNTIME_TYPE_KIND_INT16
));
73 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
74 RUNTIME_TYPE_KIND_INT32
);
75 this->add_named_type(int32_type
);
76 this->add_named_type(Type::make_integer_type("int64", false, 64,
77 RUNTIME_TYPE_KIND_INT64
));
79 this->add_named_type(Type::make_float_type("float32", 32,
80 RUNTIME_TYPE_KIND_FLOAT32
));
81 this->add_named_type(Type::make_float_type("float64", 64,
82 RUNTIME_TYPE_KIND_FLOAT64
));
84 this->add_named_type(Type::make_complex_type("complex64", 64,
85 RUNTIME_TYPE_KIND_COMPLEX64
));
86 this->add_named_type(Type::make_complex_type("complex128", 128,
87 RUNTIME_TYPE_KIND_COMPLEX128
));
89 int int_type_size
= pointer_size
;
90 if (int_type_size
< 32)
92 this->add_named_type(Type::make_integer_type("uint", true,
94 RUNTIME_TYPE_KIND_UINT
));
95 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
96 RUNTIME_TYPE_KIND_INT
);
97 this->add_named_type(int_type
);
99 this->add_named_type(Type::make_integer_type("uintptr", true,
101 RUNTIME_TYPE_KIND_UINTPTR
));
103 // "byte" is an alias for "uint8".
104 uint8_type
->integer_type()->set_is_byte();
105 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
107 this->add_named_type(byte_type
->type_value());
109 // "rune" is an alias for "int32".
110 int32_type
->integer_type()->set_is_rune();
111 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
113 this->add_named_type(rune_type
->type_value());
115 this->add_named_type(Type::make_named_bool_type());
117 this->add_named_type(Type::make_named_string_type());
119 // "error" is interface { Error() string }.
121 Typed_identifier_list
*methods
= new Typed_identifier_list
;
122 Typed_identifier_list
*results
= new Typed_identifier_list
;
123 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
124 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
125 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
126 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
127 error_iface
->finalize_methods();
128 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
129 this->add_named_type(error_type
);
132 this->globals_
->add_constant(Typed_identifier("true",
133 Type::make_boolean_type(),
136 Expression::make_boolean(true, loc
),
138 this->globals_
->add_constant(Typed_identifier("false",
139 Type::make_boolean_type(),
142 Expression::make_boolean(false, loc
),
145 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
148 Expression::make_nil(loc
),
151 Type
* abstract_int_type
= Type::make_abstract_integer_type();
152 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
155 Expression::make_iota(),
158 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
159 new_type
->set_is_varargs();
160 new_type
->set_is_builtin();
161 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
163 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
164 make_type
->set_is_varargs();
165 make_type
->set_is_builtin();
166 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
168 Typed_identifier_list
* len_result
= new Typed_identifier_list();
169 len_result
->push_back(Typed_identifier("", int_type
, loc
));
170 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
172 len_type
->set_is_builtin();
173 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
175 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
176 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
177 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
179 cap_type
->set_is_builtin();
180 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
182 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
183 print_type
->set_is_varargs();
184 print_type
->set_is_builtin();
185 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
187 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
188 print_type
->set_is_varargs();
189 print_type
->set_is_builtin();
190 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
192 Type
*empty
= Type::make_empty_interface_type(loc
);
193 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
194 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
195 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
197 panic_type
->set_is_builtin();
198 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
200 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
201 recover_result
->push_back(Typed_identifier("", empty
, loc
));
202 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
205 recover_type
->set_is_builtin();
206 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
208 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
209 close_type
->set_is_varargs();
210 close_type
->set_is_builtin();
211 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
213 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
214 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
215 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
217 copy_type
->set_is_varargs();
218 copy_type
->set_is_builtin();
219 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
221 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
222 append_type
->set_is_varargs();
223 append_type
->set_is_builtin();
224 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
226 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
227 complex_type
->set_is_varargs();
228 complex_type
->set_is_builtin();
229 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
231 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
232 real_type
->set_is_varargs();
233 real_type
->set_is_builtin();
234 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
236 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
237 imag_type
->set_is_varargs();
238 imag_type
->set_is_builtin();
239 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
241 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
242 delete_type
->set_is_varargs();
243 delete_type
->set_is_builtin();
244 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
247 // Convert a pkgpath into a string suitable for a symbol. Note that
248 // this transformation is convenient but imperfect. A -fgo-pkgpath
249 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
250 // possibly leading to link time errors.
253 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
255 std::string s
= pkgpath
;
256 for (size_t i
= 0; i
< s
.length(); ++i
)
259 if ((c
>= 'a' && c
<= 'z')
260 || (c
>= 'A' && c
<= 'Z')
261 || (c
>= '0' && c
<= '9'))
269 // Get the package path to use for type reflection data. This should
270 // ideally be unique across the entire link.
273 Gogo::pkgpath() const
275 go_assert(this->pkgpath_set_
);
276 return this->pkgpath_
;
279 // Set the package path from the -fgo-pkgpath command line option.
282 Gogo::set_pkgpath(const std::string
& arg
)
284 go_assert(!this->pkgpath_set_
);
285 this->pkgpath_
= arg
;
286 this->pkgpath_set_
= true;
287 this->pkgpath_from_option_
= true;
290 // Get the package path to use for symbol names.
293 Gogo::pkgpath_symbol() const
295 go_assert(this->pkgpath_set_
);
296 return this->pkgpath_symbol_
;
299 // Set the unique prefix to use to determine the package path, from
300 // the -fgo-prefix command line option.
303 Gogo::set_prefix(const std::string
& arg
)
305 go_assert(!this->prefix_from_option_
);
307 this->prefix_from_option_
= true;
310 // Munge name for use in an error message.
313 Gogo::message_name(const std::string
& name
)
315 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
318 // Get the package name.
321 Gogo::package_name() const
323 go_assert(this->package_
!= NULL
);
324 return this->package_
->package_name();
327 // Set the package name.
330 Gogo::set_package_name(const std::string
& package_name
,
333 if (this->package_
!= NULL
)
335 if (this->package_
->package_name() != package_name
)
336 error_at(location
, "expected package %<%s%>",
337 Gogo::message_name(this->package_
->package_name()).c_str());
341 // Now that we know the name of the package we are compiling, set
342 // the package path to use for reflect.Type.PkgPath and global
344 if (this->pkgpath_set_
)
345 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
348 if (!this->prefix_from_option_
&& package_name
== "main")
350 this->pkgpath_
= package_name
;
351 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
355 if (!this->prefix_from_option_
)
356 this->prefix_
= "go";
357 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
358 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
359 + Gogo::pkgpath_for_symbol(package_name
));
361 this->pkgpath_set_
= true;
364 this->package_
= this->register_package(this->pkgpath_
,
365 this->pkgpath_symbol_
, location
);
366 this->package_
->set_package_name(package_name
, location
);
368 if (this->is_main_package())
370 // Declare "main" as a function which takes no parameters and
372 Location uloc
= Linemap::unknown_location();
373 this->declare_function(Gogo::pack_hidden_name("main", false),
374 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
379 // Return whether this is the "main" package. This is not true if
380 // -fgo-pkgpath or -fgo-prefix was used.
383 Gogo::is_main_package() const
385 return (this->package_name() == "main"
386 && !this->pkgpath_from_option_
387 && !this->prefix_from_option_
);
393 Gogo::import_package(const std::string
& filename
,
394 const std::string
& local_name
,
395 bool is_local_name_exported
,
398 if (filename
.empty())
400 error_at(location
, "import path is empty");
404 const char *pf
= filename
.data();
405 const char *pend
= pf
+ filename
.length();
409 int adv
= Lex::fetch_char(pf
, &c
);
412 error_at(location
, "import path contains invalid UTF-8 sequence");
417 error_at(location
, "import path contains NUL");
420 if (c
< 0x20 || c
== 0x7f)
422 error_at(location
, "import path contains control character");
427 error_at(location
, "import path contains backslash; use slash");
430 if (Lex::is_unicode_space(c
))
432 error_at(location
, "import path contains space character");
435 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
437 error_at(location
, "import path contains invalid character '%c'", c
);
443 if (IS_ABSOLUTE_PATH(filename
.c_str()))
445 error_at(location
, "import path cannot be absolute path");
449 if (local_name
== "init")
450 error_at(location
, "cannot import package as init");
452 if (filename
== "unsafe")
454 this->import_unsafe(local_name
, is_local_name_exported
, location
);
455 this->current_file_imported_unsafe_
= true;
459 Imports::const_iterator p
= this->imports_
.find(filename
);
460 if (p
!= this->imports_
.end())
462 Package
* package
= p
->second
;
463 package
->set_location(location
);
464 std::string ln
= local_name
;
465 bool is_ln_exported
= is_local_name_exported
;
468 ln
= package
->package_name();
469 go_assert(!ln
.empty());
470 is_ln_exported
= Lex::is_exported_name(ln
);
476 Bindings
* bindings
= package
->bindings();
477 for (Bindings::const_declarations_iterator p
=
478 bindings
->begin_declarations();
479 p
!= bindings
->end_declarations();
481 this->add_dot_import_object(p
->second
);
482 std::string dot_alias
= "." + package
->package_name();
483 package
->add_alias(dot_alias
, location
);
487 package
->add_alias(ln
, location
);
488 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
489 this->package_
->bindings()->add_package(ln
, package
);
494 Import::Stream
* stream
= Import::open_package(filename
, location
,
495 this->relative_import_path_
);
498 error_at(location
, "import file %qs not found", filename
.c_str());
502 Import
imp(stream
, location
);
503 imp
.register_builtin_types(this);
504 Package
* package
= imp
.import(this, local_name
, is_local_name_exported
);
507 if (package
->pkgpath() == this->pkgpath())
509 ("imported package uses same package path as package "
510 "being compiled (see -fgo-pkgpath option)"));
512 this->imports_
.insert(std::make_pair(filename
, package
));
519 Gogo::lookup_init(const std::string
& init_name
)
521 Import_init
tmp("", init_name
, -1);
522 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
523 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
526 // Add an import control function for an imported package to the list.
529 Gogo::add_import_init_fn(const std::string
& package_name
,
530 const std::string
& init_name
, int prio
)
532 for (Import_init_set::iterator p
=
533 this->imported_init_fns_
.begin();
534 p
!= this->imported_init_fns_
.end();
537 Import_init
*ii
= (*p
);
538 if (ii
->init_name() == init_name
)
540 // If a test of package P1, built as part of package P1,
541 // imports package P2, and P2 imports P1 (perhaps
542 // indirectly), then we will see the same import name with
543 // different import priorities. That is OK, so don't give
544 // an error about it.
545 if (ii
->package_name() != package_name
)
547 error("duplicate package initialization name %qs",
548 Gogo::message_name(init_name
).c_str());
549 inform(UNKNOWN_LOCATION
, "used by package %qs",
550 Gogo::message_name(ii
->package_name()).c_str());
551 inform(UNKNOWN_LOCATION
, " and by package %qs",
552 Gogo::message_name(package_name
).c_str());
554 ii
->set_priority(prio
);
559 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
560 this->imported_init_fns_
.insert(nii
);
563 // Return whether we are at the global binding level.
566 Gogo::in_global_scope() const
568 return this->functions_
.empty();
571 // Return the current binding contour.
574 Gogo::current_bindings()
576 if (!this->functions_
.empty())
577 return this->functions_
.back().blocks
.back()->bindings();
578 else if (this->package_
!= NULL
)
579 return this->package_
->bindings();
581 return this->globals_
;
585 Gogo::current_bindings() const
587 if (!this->functions_
.empty())
588 return this->functions_
.back().blocks
.back()->bindings();
589 else if (this->package_
!= NULL
)
590 return this->package_
->bindings();
592 return this->globals_
;
596 Gogo::update_init_priority(Import_init
* ii
,
597 std::set
<const Import_init
*>* visited
)
602 for (std::set
<std::string
>::const_iterator pci
=
603 ii
->precursors().begin();
604 pci
!= ii
->precursors().end();
607 Import_init
* succ
= this->lookup_init(*pci
);
608 if (visited
->find(succ
) == visited
->end())
609 update_init_priority(succ
, visited
);
610 succ_prior
= std::max(succ_prior
, succ
->priority());
612 if (ii
->priority() <= succ_prior
)
613 ii
->set_priority(succ_prior
+ 1);
617 Gogo::recompute_init_priorities()
619 std::set
<Import_init
*> nonroots
;
621 for (Import_init_set::const_iterator p
=
622 this->imported_init_fns_
.begin();
623 p
!= this->imported_init_fns_
.end();
626 const Import_init
*ii
= *p
;
627 for (std::set
<std::string
>::const_iterator pci
=
628 ii
->precursors().begin();
629 pci
!= ii
->precursors().end();
632 Import_init
* ii
= this->lookup_init(*pci
);
637 // Recursively update priorities starting at roots.
638 std::set
<const Import_init
*> visited
;
639 for (Import_init_set::iterator p
=
640 this->imported_init_fns_
.begin();
641 p
!= this->imported_init_fns_
.end();
644 Import_init
* ii
= *p
;
645 if (nonroots
.find(ii
) != nonroots
.end())
647 update_init_priority(ii
, &visited
);
651 // Add statements to INIT_STMTS which run the initialization
652 // functions for imported packages. This is only used for the "main"
656 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
)
658 go_assert(this->is_main_package());
660 if (this->imported_init_fns_
.empty())
663 Location unknown_loc
= Linemap::unknown_location();
664 Function_type
* func_type
=
665 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
666 Btype
* fntype
= func_type
->get_backend_fntype(this);
668 // Recompute init priorities based on a walk of the init graph.
669 recompute_init_priorities();
671 // We must call them in increasing priority order.
672 std::vector
<const Import_init
*> v
;
673 for (Import_init_set::const_iterator p
=
674 this->imported_init_fns_
.begin();
675 p
!= this->imported_init_fns_
.end();
678 std::sort(v
.begin(), v
.end(), priority_compare
);
680 // We build calls to the init functions, which take no arguments.
681 std::vector
<Bexpression
*> empty_args
;
682 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
686 const Import_init
* ii
= *p
;
687 std::string user_name
= ii
->package_name() + ".init";
688 const std::string
& init_name(ii
->init_name());
690 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
691 true, true, true, false,
693 Bexpression
* pfunc_code
=
694 this->backend()->function_code_expression(pfunc
, unknown_loc
);
695 Bexpression
* pfunc_call
=
696 this->backend()->call_expression(pfunc_code
, empty_args
,
698 init_stmts
.push_back(this->backend()->expression_statement(pfunc_call
));
702 // Register global variables with the garbage collector. We need to
703 // register all variables which can hold a pointer value. They become
704 // roots during the mark phase. We build a struct that is easy to
705 // hook into a list of roots.
707 // struct __go_gc_root_list
709 // struct __go_gc_root_list* __next;
710 // struct __go_gc_root
717 // The last entry in the roots array has a NULL decl field.
720 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
721 std::vector
<Bstatement
*>& init_stmts
)
726 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
727 Type
* uint_type
= Type::lookup_integer_type("uint");
728 Struct_type
* root_type
= Type::make_builtin_struct_type(2,
730 "__size", uint_type
);
732 Location builtin_loc
= Linemap::predeclared_location();
733 Expression
* length
= Expression::make_integer_ul(var_gc
.size(), NULL
,
736 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
737 Type
* ptdt
= Type::make_type_descriptor_ptr_type();
738 Struct_type
* root_list_type
=
739 Type::make_builtin_struct_type(2,
741 "__roots", root_array_type
);
743 // Build an initializer for the __roots array.
745 Expression_list
* roots_init
= new Expression_list();
748 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
752 Expression_list
* init
= new Expression_list();
754 Location no_loc
= (*p
)->location();
755 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
756 Expression
* decl_addr
=
757 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
758 init
->push_back(decl_addr
);
760 Expression
* decl_size
=
761 Expression::make_type_info(decl
->type(), Expression::TYPE_INFO_SIZE
);
762 init
->push_back(decl_size
);
764 Expression
* root_ctor
=
765 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
766 roots_init
->push_back(root_ctor
);
769 // The list ends with a NULL entry.
771 Expression_list
* null_init
= new Expression_list();
772 Expression
* nil
= Expression::make_nil(builtin_loc
);
773 null_init
->push_back(nil
);
775 Expression
*zero
= Expression::make_integer_ul(0, NULL
, builtin_loc
);
776 null_init
->push_back(zero
);
778 Expression
* null_root_ctor
=
779 Expression::make_struct_composite_literal(root_type
, null_init
,
781 roots_init
->push_back(null_root_ctor
);
783 // Build a constructor for the struct.
785 Expression_list
* root_list_init
= new Expression_list();
786 root_list_init
->push_back(nil
);
788 Expression
* roots_ctor
=
789 Expression::make_array_composite_literal(root_array_type
, roots_init
,
791 root_list_init
->push_back(roots_ctor
);
793 Expression
* root_list_ctor
=
794 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
797 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
799 root_addr
->unary_expression()->set_is_gc_root();
800 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
801 builtin_loc
, 1, root_addr
);
803 Translate_context
context(this, NULL
, NULL
, NULL
);
804 Bexpression
* bcall
= register_roots
->get_backend(&context
);
805 init_stmts
.push_back(this->backend()->expression_statement(bcall
));
808 // Get the name to use for the import control function. If there is a
809 // global function or variable, then we know that that name must be
810 // unique in the link, and we use it as the basis for our name.
813 Gogo::get_init_fn_name()
815 if (this->init_fn_name_
.empty())
817 go_assert(this->package_
!= NULL
);
818 if (this->is_main_package())
820 // Use a name which the runtime knows.
821 this->init_fn_name_
= "__go_init_main";
825 std::string s
= this->pkgpath_symbol();
826 s
.append("..import");
827 this->init_fn_name_
= s
;
831 return this->init_fn_name_
;
834 // Build the decl for the initialization function.
837 Gogo::initialization_function_decl()
839 std::string name
= this->get_init_fn_name();
840 Location loc
= this->package_
->location();
842 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
843 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
844 return Named_object::make_function(name
, NULL
, initfn
);
847 // Create the magic initialization function. CODE_STMT is the
848 // code that it needs to run.
851 Gogo::create_initialization_function(Named_object
* initfn
,
852 Bstatement
* code_stmt
)
854 // Make sure that we thought we needed an initialization function,
855 // as otherwise we will not have reported it in the export data.
856 go_assert(this->is_main_package() || this->need_init_fn_
);
859 initfn
= this->initialization_function_decl();
861 // Bind the initialization function code to a block.
862 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
863 Location pkg_loc
= this->package_
->location();
864 std::vector
<Bvariable
*> vars
;
865 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
867 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
869 go_assert(saw_errors());
875 // Search for references to VAR in any statements or called functions.
877 class Find_var
: public Traverse
880 // A hash table we use to avoid looping. The index is the name of a
881 // named object. We only look through objects defined in this
883 typedef Unordered_set(const void*) Seen_objects
;
885 Find_var(Named_object
* var
, Seen_objects
* seen_objects
)
886 : Traverse(traverse_expressions
),
887 var_(var
), seen_objects_(seen_objects
), found_(false)
890 // Whether the variable was found.
893 { return this->found_
; }
896 expression(Expression
**);
899 // The variable we are looking for.
901 // Names of objects we have already seen.
902 Seen_objects
* seen_objects_
;
903 // True if the variable was found.
907 // See if EXPR refers to VAR, looking through function calls and
908 // variable initializations.
911 Find_var::expression(Expression
** pexpr
)
913 Expression
* e
= *pexpr
;
915 Var_expression
* ve
= e
->var_expression();
918 Named_object
* v
= ve
->named_object();
922 return TRAVERSE_EXIT
;
925 if (v
->is_variable() && v
->package() == NULL
)
927 Expression
* init
= v
->var_value()->init();
930 std::pair
<Seen_objects::iterator
, bool> ins
=
931 this->seen_objects_
->insert(v
);
934 // This is the first time we have seen this name.
935 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
936 return TRAVERSE_EXIT
;
942 // We traverse the code of any function or bound method we see. Note that
943 // this means that we will traverse the code of a function or bound method
944 // whose address is taken even if it is not called.
945 Func_expression
* fe
= e
->func_expression();
946 Bound_method_expression
* bme
= e
->bound_method_expression();
947 if (fe
!= NULL
|| bme
!= NULL
)
949 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
950 if (f
->is_function() && f
->package() == NULL
)
952 std::pair
<Seen_objects::iterator
, bool> ins
=
953 this->seen_objects_
->insert(f
);
956 // This is the first time we have seen this name.
957 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
958 return TRAVERSE_EXIT
;
963 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
966 Temporary_statement
* ts
= tre
->statement();
967 Expression
* init
= ts
->init();
970 std::pair
<Seen_objects::iterator
, bool> ins
=
971 this->seen_objects_
->insert(ts
);
974 // This is the first time we have seen this temporary
976 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
977 return TRAVERSE_EXIT
;
982 return TRAVERSE_CONTINUE
;
985 // Return true if EXPR, PREINIT, or DEP refers to VAR.
988 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
991 Find_var::Seen_objects seen_objects
;
992 Find_var
find_var(var
, &seen_objects
);
994 Expression::traverse(&expr
, &find_var
);
996 preinit
->traverse(&find_var
);
999 Expression
* init
= dep
->var_value()->init();
1001 Expression::traverse(&init
, &find_var
);
1002 if (dep
->var_value()->has_pre_init())
1003 dep
->var_value()->preinit()->traverse(&find_var
);
1006 return find_var
.found();
1009 // Sort variable initializations. If the initialization expression
1010 // for variable A refers directly or indirectly to the initialization
1011 // expression for variable B, then we must initialize B before A.
1017 : var_(NULL
), init_(NULL
), dep_count_(0)
1020 Var_init(Named_object
* var
, Bstatement
* init
)
1021 : var_(var
), init_(init
), dep_count_(0)
1024 // Return the variable.
1027 { return this->var_
; }
1029 // Return the initialization expression.
1032 { return this->init_
; }
1034 // Return the number of remaining dependencies.
1037 { return this->dep_count_
; }
1039 // Increment the number of dependencies.
1042 { ++this->dep_count_
; }
1044 // Decrement the number of dependencies.
1047 { --this->dep_count_
; }
1050 // The variable being initialized.
1052 // The initialization statement.
1054 // The number of initializations this is dependent on. A variable
1055 // initialization should not be emitted if any of its dependencies
1056 // have not yet been resolved.
1060 // For comparing Var_init keys in a map.
1063 operator<(const Var_init
& v1
, const Var_init
& v2
)
1064 { return v1
.var()->name() < v2
.var()->name(); }
1066 typedef std::list
<Var_init
> Var_inits
;
1068 // Sort the variable initializations. The rule we follow is that we
1069 // emit them in the order they appear in the array, except that if the
1070 // initialization expression for a variable V1 depends upon another
1071 // variable V2 then we initialize V1 after V2.
1074 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1076 if (var_inits
->empty())
1079 typedef std::pair
<Named_object
*, Named_object
*> No_no
;
1080 typedef std::map
<No_no
, bool> Cache
;
1083 // A mapping from a variable initialization to a set of
1084 // variable initializations that depend on it.
1085 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1086 Init_deps init_deps
;
1087 bool init_loop
= false;
1088 for (Var_inits::iterator p1
= var_inits
->begin();
1089 p1
!= var_inits
->end();
1092 Named_object
* var
= p1
->var();
1093 Expression
* init
= var
->var_value()->init();
1094 Block
* preinit
= var
->var_value()->preinit();
1095 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1097 // Start walking through the list to see which variables VAR
1098 // needs to wait for.
1099 for (Var_inits::iterator p2
= var_inits
->begin();
1100 p2
!= var_inits
->end();
1103 if (var
== p2
->var())
1106 Named_object
* p2var
= p2
->var();
1107 No_no
key(var
, p2var
);
1108 std::pair
<Cache::iterator
, bool> ins
=
1109 cache
.insert(std::make_pair(key
, false));
1111 ins
.first
->second
= expression_requires(init
, preinit
, dep
, p2var
);
1112 if (ins
.first
->second
)
1114 // VAR depends on P2VAR.
1115 init_deps
[*p2
].insert(&(*p1
));
1116 p1
->add_dependency();
1118 // Check for cycles.
1119 key
= std::make_pair(p2var
, var
);
1120 ins
= cache
.insert(std::make_pair(key
, false));
1123 expression_requires(p2var
->var_value()->init(),
1124 p2var
->var_value()->preinit(),
1125 gogo
->var_depends_on(p2var
->var_value()),
1127 if (ins
.first
->second
)
1129 error_at(var
->location(),
1130 ("initialization expressions for %qs and "
1131 "%qs depend upon each other"),
1132 var
->message_name().c_str(),
1133 p2var
->message_name().c_str());
1134 inform(p2
->var()->location(), "%qs defined here",
1135 p2var
->message_name().c_str());
1143 // If there are no dependencies then the declaration order is sorted.
1144 if (!init_deps
.empty() && !init_loop
)
1146 // Otherwise, sort variable initializations by emitting all variables with
1147 // no dependencies in declaration order. VAR_INITS is already in
1148 // declaration order.
1150 while (!var_inits
->empty())
1152 Var_inits::iterator v1
;;
1153 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1155 if (v1
->dep_count() == 0)
1158 go_assert(v1
!= var_inits
->end());
1160 // V1 either has no dependencies or its dependencies have already
1161 // been emitted, add it to READY next. When V1 is emitted, remove
1162 // a dependency from each V that depends on V1.
1163 ready
.splice(ready
.end(), *var_inits
, v1
);
1165 Init_deps::iterator p1
= init_deps
.find(*v1
);
1166 if (p1
!= init_deps
.end())
1168 std::set
<Var_init
*> resolved
= p1
->second
;
1169 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1170 pv
!= resolved
.end();
1172 (*pv
)->remove_dependency();
1173 init_deps
.erase(p1
);
1176 var_inits
->swap(ready
);
1177 go_assert(init_deps
.empty());
1180 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1181 // check for a loop of VAR on itself. We only do this if
1182 // INIT is not NULL and there is no dependency; when INIT is
1183 // NULL, it means that PREINIT sets VAR, which we will
1184 // interpret as a loop.
1185 for (Var_inits::const_iterator p
= var_inits
->begin();
1186 p
!= var_inits
->end();
1189 Named_object
* var
= p
->var();
1190 Expression
* init
= var
->var_value()->init();
1191 Block
* preinit
= var
->var_value()->preinit();
1192 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1193 if (init
!= NULL
&& dep
== NULL
1194 && expression_requires(init
, preinit
, NULL
, var
))
1195 error_at(var
->location(),
1196 "initialization expression for %qs depends upon itself",
1197 var
->message_name().c_str());
1201 // Write out the global definitions.
1204 Gogo::write_globals()
1206 this->build_interface_method_tables();
1208 Bindings
* bindings
= this->current_bindings();
1210 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1211 p
!= bindings
->end_declarations();
1214 // If any function declarations needed a descriptor, make sure
1216 Named_object
* no
= p
->second
;
1217 if (no
->is_function_declaration())
1218 no
->func_declaration_value()->build_backend_descriptor(this);
1221 // Lists of globally declared types, variables, constants, and functions
1222 // that must be defined.
1223 std::vector
<Btype
*> type_decls
;
1224 std::vector
<Bvariable
*> var_decls
;
1225 std::vector
<Bexpression
*> const_decls
;
1226 std::vector
<Bfunction
*> func_decls
;
1228 // The init function declaration, if necessary.
1229 Named_object
* init_fndecl
= NULL
;
1231 std::vector
<Bstatement
*> init_stmts
;
1232 std::vector
<Bstatement
*> var_init_stmts
;
1234 if (this->is_main_package())
1235 this->init_imports(init_stmts
);
1237 // A list of variable initializations.
1238 Var_inits var_inits
;
1240 // A list of variables which need to be registered with the garbage
1242 size_t count_definitions
= bindings
->size_definitions();
1243 std::vector
<Named_object
*> var_gc
;
1244 var_gc
.reserve(count_definitions
);
1246 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1247 p
!= bindings
->end_definitions();
1250 Named_object
* no
= *p
;
1251 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1253 // There is nothing to do for a package.
1254 if (no
->is_package())
1257 // There is nothing to do for an object which was imported from
1258 // a different package into the global scope.
1259 if (no
->package() != NULL
)
1262 // Skip blank named functions and constants.
1263 if ((no
->is_function() && no
->func_value()->is_sink())
1264 || (no
->is_const() && no
->const_value()->is_sink()))
1267 // There is nothing useful we can output for constants which
1268 // have ideal or non-integral type.
1271 Type
* type
= no
->const_value()->type();
1273 type
= no
->const_value()->expr()->type();
1274 if (type
->is_abstract() || !type
->is_numeric_type())
1278 if (!no
->is_variable())
1279 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1282 Variable
* var
= no
->var_value();
1283 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1284 var_decls
.push_back(bvar
);
1286 // Check for a sink variable, which may be used to run an
1287 // initializer purely for its side effects.
1288 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1290 Bstatement
* var_init_stmt
= NULL
;
1291 if (!var
->has_pre_init())
1293 // If the backend representation of the variable initializer is
1294 // constant, we can just set the initial value using
1295 // global_var_set_init instead of during the init() function.
1296 // The initializer is constant if it is the zero-value of the
1297 // variable's type or if the initial value is an immutable value
1298 // that is not copied to the heap.
1299 bool is_constant_initializer
= false;
1300 if (var
->init() == NULL
)
1301 is_constant_initializer
= true;
1304 Type
* var_type
= var
->type();
1305 Expression
* init
= var
->init();
1306 Expression
* init_cast
=
1307 Expression::make_cast(var_type
, init
, var
->location());
1308 is_constant_initializer
=
1309 init_cast
->is_immutable() && !var_type
->has_pointer();
1312 // Non-constant variable initializations might need to create
1313 // temporary variables, which will need the initialization
1314 // function as context.
1315 if (!is_constant_initializer
&& init_fndecl
== NULL
)
1316 init_fndecl
= this->initialization_function_decl();
1317 Bexpression
* var_binit
= var
->get_init(this, init_fndecl
);
1319 if (var_binit
== NULL
)
1321 else if (is_constant_initializer
)
1323 if (expression_requires(var
->init(), NULL
,
1324 this->var_depends_on(var
), no
))
1325 error_at(no
->location(),
1326 "initialization expression for %qs depends "
1328 no
->message_name().c_str());
1329 this->backend()->global_variable_set_init(bvar
, var_binit
);
1333 this->backend()->expression_statement(var_binit
);
1336 Location loc
= var
->location();
1337 Bexpression
* var_expr
=
1338 this->backend()->var_expression(bvar
, loc
);
1340 this->backend()->assignment_statement(var_expr
, var_binit
,
1346 // We are going to create temporary variables which
1347 // means that we need an fndecl.
1348 if (init_fndecl
== NULL
)
1349 init_fndecl
= this->initialization_function_decl();
1351 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1352 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1355 if (var_init_stmt
!= NULL
)
1357 if (var
->init() == NULL
&& !var
->has_pre_init())
1358 var_init_stmts
.push_back(var_init_stmt
);
1360 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1362 else if (this->var_depends_on(var
) != NULL
)
1364 // This variable is initialized from something that is
1365 // not in its init or preinit. This variable needs to
1366 // participate in dependency analysis sorting, in case
1367 // some other variable depends on this one.
1368 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1369 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1370 Bstatement
* zero_stmt
=
1371 this->backend()->expression_statement(zero
);
1372 var_inits
.push_back(Var_init(no
, zero_stmt
));
1375 if (!is_sink
&& var
->type()->has_pointer())
1376 var_gc
.push_back(no
);
1380 // Register global variables with the garbage collector.
1381 this->register_gc_vars(var_gc
, init_stmts
);
1383 // Simple variable initializations, after all variables are
1385 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1387 // Complete variable initializations, first sorting them into a
1389 if (!var_inits
.empty())
1391 sort_var_inits(this, &var_inits
);
1392 for (Var_inits::const_iterator p
= var_inits
.begin();
1393 p
!= var_inits
.end();
1395 init_stmts
.push_back(p
->init());
1398 // After all the variables are initialized, call the init
1399 // functions if there are any. Init functions take no arguments, so
1400 // we pass in EMPTY_ARGS to call them.
1401 std::vector
<Bexpression
*> empty_args
;
1402 for (std::vector
<Named_object
*>::const_iterator p
=
1403 this->init_functions_
.begin();
1404 p
!= this->init_functions_
.end();
1407 Location func_loc
= (*p
)->location();
1408 Function
* func
= (*p
)->func_value();
1409 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1410 Bexpression
* func_code
=
1411 this->backend()->function_code_expression(initfn
, func_loc
);
1412 Bexpression
* call
= this->backend()->call_expression(func_code
,
1415 init_stmts
.push_back(this->backend()->expression_statement(call
));
1418 // Set up a magic function to do all the initialization actions.
1419 // This will be called if this package is imported.
1420 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1421 if (this->need_init_fn_
|| this->is_main_package())
1424 this->create_initialization_function(init_fndecl
, init_fncode
);
1425 if (init_fndecl
!= NULL
)
1426 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1429 // We should not have seen any new bindings created during the conversion.
1430 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1432 // Define all globally declared values.
1434 this->backend()->write_global_definitions(type_decls
, const_decls
,
1435 func_decls
, var_decls
);
1438 // Return the current block.
1441 Gogo::current_block()
1443 if (this->functions_
.empty())
1446 return this->functions_
.back().blocks
.back();
1449 // Look up a name in the current binding contour. If PFUNCTION is not
1450 // NULL, set it to the function in which the name is defined, or NULL
1451 // if the name is defined in global scope.
1454 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1456 if (pfunction
!= NULL
)
1459 if (Gogo::is_sink_name(name
))
1460 return Named_object::make_sink();
1462 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1463 p
!= this->functions_
.rend();
1466 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1469 if (pfunction
!= NULL
)
1470 *pfunction
= p
->function
;
1475 if (this->package_
!= NULL
)
1477 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1480 if (ret
->package() != NULL
)
1482 std::string dot_alias
= "." + ret
->package()->package_name();
1483 ret
->package()->note_usage(dot_alias
);
1489 // We do not look in the global namespace. If we did, the global
1490 // namespace would effectively hide names which were defined in
1491 // package scope which we have not yet seen. Instead,
1492 // define_global_names is called after parsing is over to connect
1493 // undefined names at package scope with names defined at global
1499 // Look up a name in the current block, without searching enclosing
1503 Gogo::lookup_in_block(const std::string
& name
) const
1505 go_assert(!this->functions_
.empty());
1506 go_assert(!this->functions_
.back().blocks
.empty());
1507 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1510 // Look up a name in the global namespace.
1513 Gogo::lookup_global(const char* name
) const
1515 return this->globals_
->lookup(name
);
1518 // Add an imported package.
1521 Gogo::add_imported_package(const std::string
& real_name
,
1522 const std::string
& alias_arg
,
1523 bool is_alias_exported
,
1524 const std::string
& pkgpath
,
1525 const std::string
& pkgpath_symbol
,
1527 bool* padd_to_globals
)
1529 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1530 ret
->set_package_name(real_name
, location
);
1532 *padd_to_globals
= false;
1534 if (alias_arg
== "_")
1536 else if (alias_arg
== ".")
1538 *padd_to_globals
= true;
1539 std::string dot_alias
= "." + real_name
;
1540 ret
->add_alias(dot_alias
, location
);
1544 std::string alias
= alias_arg
;
1548 is_alias_exported
= Lex::is_exported_name(alias
);
1550 ret
->add_alias(alias
, location
);
1551 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1552 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1553 if (!no
->is_package())
1560 // Register a package. This package may or may not be imported. This
1561 // returns the Package structure for the package, creating if it
1562 // necessary. LOCATION is the location of the import statement that
1563 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1564 // for names in the package; it may be the empty string, in which case
1565 // we either get it later or make a guess when we need it.
1568 Gogo::register_package(const std::string
& pkgpath
,
1569 const std::string
& pkgpath_symbol
, Location location
)
1571 Package
* package
= NULL
;
1572 std::pair
<Packages::iterator
, bool> ins
=
1573 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1576 // We have seen this package name before.
1577 package
= ins
.first
->second
;
1578 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1579 if (!pkgpath_symbol
.empty())
1580 package
->set_pkgpath_symbol(pkgpath_symbol
);
1581 if (Linemap::is_unknown_location(package
->location()))
1582 package
->set_location(location
);
1586 // First time we have seen this package name.
1587 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1588 go_assert(ins
.first
->second
== NULL
);
1589 ins
.first
->second
= package
;
1595 // Start compiling a function.
1598 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1599 bool add_method_to_type
, Location location
)
1601 bool at_top_level
= this->functions_
.empty();
1603 Block
* block
= new Block(NULL
, location
);
1605 Named_object
* enclosing
= (at_top_level
1607 : this->functions_
.back().function
);
1609 Function
* function
= new Function(type
, enclosing
, block
, location
);
1611 if (type
->is_method())
1613 const Typed_identifier
* receiver
= type
->receiver();
1614 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1615 true, true, location
);
1616 std::string rname
= receiver
->name();
1617 if (rname
.empty() || Gogo::is_sink_name(rname
))
1619 // We need to give receivers a name since they wind up in
1620 // DECL_ARGUMENTS. FIXME.
1621 static unsigned int count
;
1623 snprintf(buf
, sizeof buf
, "r.%u", count
);
1627 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1630 const Typed_identifier_list
* parameters
= type
->parameters();
1631 bool is_varargs
= type
->is_varargs();
1632 if (parameters
!= NULL
)
1634 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1635 p
!= parameters
->end();
1638 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1640 if (is_varargs
&& p
+ 1 == parameters
->end())
1641 param
->set_is_varargs_parameter();
1643 std::string pname
= p
->name();
1644 if (pname
.empty() || Gogo::is_sink_name(pname
))
1646 // We need to give parameters a name since they wind up
1647 // in DECL_ARGUMENTS. FIXME.
1648 static unsigned int count
;
1650 snprintf(buf
, sizeof buf
, "p.%u", count
);
1654 block
->bindings()->add_variable(pname
, NULL
, param
);
1658 function
->create_result_variables(this);
1660 const std::string
* pname
;
1661 std::string nested_name
;
1662 bool is_init
= false;
1663 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
1665 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
1666 || (type
->results() != NULL
&& !type
->results()->empty()))
1668 "func init must have no arguments and no return values");
1669 // There can be multiple "init" functions, so give them each a
1671 static int init_count
;
1673 snprintf(buf
, sizeof buf
, ".$init%d", init_count
);
1676 pname
= &nested_name
;
1679 else if (!name
.empty())
1683 // Invent a name for a nested function.
1684 static int nested_count
;
1686 snprintf(buf
, sizeof buf
, ".$nested%d", nested_count
);
1689 pname
= &nested_name
;
1693 if (Gogo::is_sink_name(*pname
))
1695 static int sink_count
;
1697 snprintf(buf
, sizeof buf
, ".$sink%d", sink_count
);
1699 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1700 ret
->func_value()->set_is_sink();
1702 else if (!type
->is_method())
1704 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
1705 if (!ret
->is_function() || ret
->func_value() != function
)
1707 // Redefinition error. Invent a name to avoid knockon
1709 static int redefinition_count
;
1711 snprintf(buf
, sizeof buf
, ".$redefined%d", redefinition_count
);
1712 ++redefinition_count
;
1713 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1718 if (!add_method_to_type
)
1719 ret
= Named_object::make_function(name
, NULL
, function
);
1722 go_assert(at_top_level
);
1723 Type
* rtype
= type
->receiver()->type();
1725 // We want to look through the pointer created by the
1726 // parser, without getting an error if the type is not yet
1728 if (rtype
->classification() == Type::TYPE_POINTER
)
1729 rtype
= rtype
->points_to();
1731 if (rtype
->is_error_type())
1732 ret
= Named_object::make_function(name
, NULL
, function
);
1733 else if (rtype
->named_type() != NULL
)
1735 ret
= rtype
->named_type()->add_method(name
, function
);
1736 if (!ret
->is_function())
1738 // Redefinition error.
1739 ret
= Named_object::make_function(name
, NULL
, function
);
1742 else if (rtype
->forward_declaration_type() != NULL
)
1744 Named_object
* type_no
=
1745 rtype
->forward_declaration_type()->named_object();
1746 if (type_no
->is_unknown())
1748 // If we are seeing methods it really must be a
1749 // type. Declare it as such. An alternative would
1750 // be to support lists of methods for unknown
1751 // expressions. Either way the error messages if
1752 // this is not a type are going to get confusing.
1753 Named_object
* declared
=
1754 this->declare_package_type(type_no
->name(),
1755 type_no
->location());
1757 == type_no
->unknown_value()->real_named_object());
1759 ret
= rtype
->forward_declaration_type()->add_method(name
,
1764 error_at(type
->receiver()->location(),
1765 "invalid receiver type (receiver must be a named type)");
1766 ret
= Named_object::make_function(name
, NULL
, function
);
1769 this->package_
->bindings()->add_method(ret
);
1772 this->functions_
.resize(this->functions_
.size() + 1);
1773 Open_function
& of(this->functions_
.back());
1775 of
.blocks
.push_back(block
);
1779 this->init_functions_
.push_back(ret
);
1780 this->need_init_fn_
= true;
1786 // Finish compiling a function.
1789 Gogo::finish_function(Location location
)
1791 this->finish_block(location
);
1792 go_assert(this->functions_
.back().blocks
.empty());
1793 this->functions_
.pop_back();
1796 // Return the current function.
1799 Gogo::current_function() const
1801 go_assert(!this->functions_
.empty());
1802 return this->functions_
.back().function
;
1805 // Start a new block.
1808 Gogo::start_block(Location location
)
1810 go_assert(!this->functions_
.empty());
1811 Block
* block
= new Block(this->current_block(), location
);
1812 this->functions_
.back().blocks
.push_back(block
);
1818 Gogo::finish_block(Location location
)
1820 go_assert(!this->functions_
.empty());
1821 go_assert(!this->functions_
.back().blocks
.empty());
1822 Block
* block
= this->functions_
.back().blocks
.back();
1823 this->functions_
.back().blocks
.pop_back();
1824 block
->set_end_location(location
);
1828 // Add an erroneous name.
1831 Gogo::add_erroneous_name(const std::string
& name
)
1833 return this->package_
->bindings()->add_erroneous_name(name
);
1836 // Add an unknown name.
1839 Gogo::add_unknown_name(const std::string
& name
, Location location
)
1841 return this->package_
->bindings()->add_unknown_name(name
, location
);
1844 // Declare a function.
1847 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
1850 if (!type
->is_method())
1851 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
1855 // We don't bother to add this to the list of global
1857 Type
* rtype
= type
->receiver()->type();
1859 // We want to look through the pointer created by the
1860 // parser, without getting an error if the type is not yet
1862 if (rtype
->classification() == Type::TYPE_POINTER
)
1863 rtype
= rtype
->points_to();
1865 if (rtype
->is_error_type())
1867 else if (rtype
->named_type() != NULL
)
1868 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
1870 else if (rtype
->forward_declaration_type() != NULL
)
1872 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
1873 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
1877 error_at(type
->receiver()->location(),
1878 "invalid receiver type (receiver must be a named type)");
1879 return Named_object::make_erroneous_name(name
);
1884 // Add a label definition.
1887 Gogo::add_label_definition(const std::string
& label_name
,
1890 go_assert(!this->functions_
.empty());
1891 Function
* func
= this->functions_
.back().function
->func_value();
1892 Label
* label
= func
->add_label_definition(this, label_name
, location
);
1893 this->add_statement(Statement::make_label_statement(label
, location
));
1897 // Add a label reference.
1900 Gogo::add_label_reference(const std::string
& label_name
,
1901 Location location
, bool issue_goto_errors
)
1903 go_assert(!this->functions_
.empty());
1904 Function
* func
= this->functions_
.back().function
->func_value();
1905 return func
->add_label_reference(this, label_name
, location
,
1909 // Return the current binding state.
1912 Gogo::bindings_snapshot(Location location
)
1914 return new Bindings_snapshot(this->current_block(), location
);
1920 Gogo::add_statement(Statement
* statement
)
1922 go_assert(!this->functions_
.empty()
1923 && !this->functions_
.back().blocks
.empty());
1924 this->functions_
.back().blocks
.back()->add_statement(statement
);
1930 Gogo::add_block(Block
* block
, Location location
)
1932 go_assert(!this->functions_
.empty()
1933 && !this->functions_
.back().blocks
.empty());
1934 Statement
* statement
= Statement::make_block_statement(block
, location
);
1935 this->functions_
.back().blocks
.back()->add_statement(statement
);
1941 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
1944 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
1950 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
1952 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
1954 if (!this->in_global_scope() && no
->is_type())
1956 Named_object
* f
= this->functions_
.back().function
;
1958 if (f
->is_function())
1959 index
= f
->func_value()->new_local_type_index();
1962 no
->type_value()->set_in_function(f
, index
);
1966 // Add a named type.
1969 Gogo::add_named_type(Named_type
* type
)
1971 go_assert(this->in_global_scope());
1972 this->current_bindings()->add_named_type(type
);
1978 Gogo::declare_type(const std::string
& name
, Location location
)
1980 Bindings
* bindings
= this->current_bindings();
1981 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
1982 if (!this->in_global_scope() && no
->is_type_declaration())
1984 Named_object
* f
= this->functions_
.back().function
;
1986 if (f
->is_function())
1987 index
= f
->func_value()->new_local_type_index();
1990 no
->type_declaration_value()->set_in_function(f
, index
);
1995 // Declare a type at the package level.
1998 Gogo::declare_package_type(const std::string
& name
, Location location
)
2000 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2003 // Declare a function at the package level.
2006 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2009 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2013 // Define a type which was already declared.
2016 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2018 this->current_bindings()->define_type(no
, type
);
2024 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2026 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2029 // In a function the middle-end wants to see a DECL_EXPR node.
2031 && no
->is_variable()
2032 && !no
->var_value()->is_parameter()
2033 && !this->functions_
.empty())
2034 this->add_statement(Statement::make_variable_declaration(no
));
2039 // Add a sink--a reference to the blank identifier _.
2044 return Named_object::make_sink();
2047 // Add a named object for a dot import.
2050 Gogo::add_dot_import_object(Named_object
* no
)
2052 // If the name already exists, then it was defined in some file seen
2053 // earlier. If the earlier name is just a declaration, don't add
2054 // this name, because that will cause the previous declaration to
2055 // merge to this imported name, which should not happen. Just add
2056 // this name to the list of file block names to get appropriate
2057 // errors if we see a later definition.
2058 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2059 if (e
!= NULL
&& e
->package() == NULL
)
2061 if (e
->is_unknown())
2063 if (e
->package() == NULL
2064 && (e
->is_type_declaration()
2065 || e
->is_function_declaration()
2066 || e
->is_unknown()))
2068 this->add_file_block_name(no
->name(), no
->location());
2073 this->current_bindings()->add_named_object(no
);
2076 // Add a linkname. This implements the go:linkname compiler directive.
2077 // We only support this for functions and function declarations.
2080 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2081 const std::string
& ext_name
, Location loc
)
2084 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2087 error_at(loc
, "%s is not defined", go_name
.c_str());
2088 else if (no
->is_function())
2089 no
->func_value()->set_asm_name(ext_name
);
2090 else if (no
->is_function_declaration())
2091 no
->func_declaration_value()->set_asm_name(ext_name
);
2094 ("%s is not a function; "
2095 "//go:linkname is only supported for functions"),
2099 // Mark all local variables used. This is used when some types of
2100 // parse error occur.
2103 Gogo::mark_locals_used()
2105 for (Open_functions::iterator pf
= this->functions_
.begin();
2106 pf
!= this->functions_
.end();
2109 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2110 pb
!= pf
->blocks
.end();
2112 (*pb
)->bindings()->mark_locals_used();
2116 // Record that we've seen an interface type.
2119 Gogo::record_interface_type(Interface_type
* itype
)
2121 this->interface_types_
.push_back(itype
);
2124 // Return an erroneous name that indicates that an error has already
2128 Gogo::erroneous_name()
2130 static int erroneous_count
;
2132 snprintf(name
, sizeof name
, "$erroneous%d", erroneous_count
);
2137 // Return whether a name is an erroneous name.
2140 Gogo::is_erroneous_name(const std::string
& name
)
2142 return name
.compare(0, 10, "$erroneous") == 0;
2145 // Return a name for a thunk object.
2150 static int thunk_count
;
2151 char thunk_name
[50];
2152 snprintf(thunk_name
, sizeof thunk_name
, "$thunk%d", thunk_count
);
2157 // Return whether a function is a thunk.
2160 Gogo::is_thunk(const Named_object
* no
)
2162 return no
->name().compare(0, 6, "$thunk") == 0;
2165 // Define the global names. We do this only after parsing all the
2166 // input files, because the program might define the global names
2170 Gogo::define_global_names()
2172 for (Bindings::const_declarations_iterator p
=
2173 this->globals_
->begin_declarations();
2174 p
!= this->globals_
->end_declarations();
2177 Named_object
* global_no
= p
->second
;
2178 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2179 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2183 if (no
->is_type_declaration())
2185 if (global_no
->is_type())
2187 if (no
->type_declaration_value()->has_methods())
2188 error_at(no
->location(),
2189 "may not define methods for global type");
2190 no
->set_type_value(global_no
->type_value());
2194 error_at(no
->location(), "expected type");
2195 Type
* errtype
= Type::make_error_type();
2197 Named_object::make_type("erroneous_type", NULL
, errtype
,
2198 Linemap::predeclared_location());
2199 no
->set_type_value(err
->type_value());
2202 else if (no
->is_unknown())
2203 no
->unknown_value()->set_real_named_object(global_no
);
2206 // Give an error if any name is defined in both the package block
2207 // and the file block. For example, this can happen if one file
2208 // imports "fmt" and another file defines a global variable fmt.
2209 for (Bindings::const_declarations_iterator p
=
2210 this->package_
->bindings()->begin_declarations();
2211 p
!= this->package_
->bindings()->end_declarations();
2214 if (p
->second
->is_unknown()
2215 && p
->second
->unknown_value()->real_named_object() == NULL
)
2217 // No point in warning about an undefined name, as we will
2218 // get other errors later anyhow.
2221 File_block_names::const_iterator pf
=
2222 this->file_block_names_
.find(p
->second
->name());
2223 if (pf
!= this->file_block_names_
.end())
2225 std::string n
= p
->second
->message_name();
2226 error_at(p
->second
->location(),
2227 "%qs defined as both imported name and global name",
2229 inform(pf
->second
, "%qs imported here", n
.c_str());
2232 // No package scope identifier may be named "init".
2233 if (!p
->second
->is_function()
2234 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2236 error_at(p
->second
->location(),
2237 "cannot declare init - must be func");
2242 // Clear out names in file scope.
2245 Gogo::clear_file_scope()
2247 this->package_
->bindings()->clear_file_scope(this);
2249 // Warn about packages which were imported but not used.
2250 bool quiet
= saw_errors();
2251 for (Packages::iterator p
= this->packages_
.begin();
2252 p
!= this->packages_
.end();
2255 Package
* package
= p
->second
;
2256 if (package
!= this->package_
&& !quiet
)
2258 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2259 p1
!= package
->aliases().end();
2262 if (!p1
->second
->used())
2264 // Give a more refined error message if the alias name is known.
2265 std::string pkg_name
= package
->package_name();
2266 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2268 error_at(p1
->second
->location(),
2269 "imported and not used: %s as %s",
2270 Gogo::message_name(pkg_name
).c_str(),
2271 Gogo::message_name(p1
->first
).c_str());
2274 error_at(p1
->second
->location(),
2275 "imported and not used: %s",
2276 Gogo::message_name(pkg_name
).c_str());
2280 package
->clear_used();
2283 this->current_file_imported_unsafe_
= false;
2286 // Queue up a type specific function for later writing. These are
2287 // written out in write_specific_type_functions, called after the
2288 // parse tree is lowered.
2291 Gogo::queue_specific_type_function(Type
* type
, Named_type
* name
,
2292 const std::string
& hash_name
,
2293 Function_type
* hash_fntype
,
2294 const std::string
& equal_name
,
2295 Function_type
* equal_fntype
)
2297 go_assert(!this->specific_type_functions_are_written_
);
2298 go_assert(!this->in_global_scope());
2299 Specific_type_function
* tsf
= new Specific_type_function(type
, name
,
2304 this->specific_type_functions_
.push_back(tsf
);
2307 // Look for types which need specific hash or equality functions.
2309 class Specific_type_functions
: public Traverse
2312 Specific_type_functions(Gogo
* gogo
)
2313 : Traverse(traverse_types
),
2325 Specific_type_functions::type(Type
* t
)
2327 Named_object
* hash_fn
;
2328 Named_object
* equal_fn
;
2329 switch (t
->classification())
2331 case Type::TYPE_NAMED
:
2333 Named_type
* nt
= t
->named_type();
2334 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2335 t
->type_functions(this->gogo_
, nt
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2337 // If this is a struct type, we don't want to make functions
2338 // for the unnamed struct.
2339 Type
* rt
= nt
->real_type();
2340 if (rt
->struct_type() == NULL
)
2342 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2343 return TRAVERSE_EXIT
;
2347 // If this type is defined in another package, then we don't
2348 // need to worry about the unexported fields.
2349 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2350 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2351 for (Struct_field_list::const_iterator p
= fields
->begin();
2355 if (is_defined_elsewhere
2356 && Gogo::is_hidden_name(p
->field_name()))
2358 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2359 return TRAVERSE_EXIT
;
2363 return TRAVERSE_SKIP_COMPONENTS
;
2366 case Type::TYPE_STRUCT
:
2367 case Type::TYPE_ARRAY
:
2368 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2369 t
->type_functions(this->gogo_
, NULL
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2376 return TRAVERSE_CONTINUE
;
2379 // Write out type specific functions.
2382 Gogo::write_specific_type_functions()
2384 Specific_type_functions
stf(this);
2385 this->traverse(&stf
);
2387 while (!this->specific_type_functions_
.empty())
2389 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2390 this->specific_type_functions_
.pop_back();
2391 tsf
->type
->write_specific_type_functions(this, tsf
->name
,
2398 this->specific_type_functions_are_written_
= true;
2401 // Traverse the tree.
2404 Gogo::traverse(Traverse
* traverse
)
2406 // Traverse the current package first for consistency. The other
2407 // packages will only contain imported types, constants, and
2409 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2411 for (Packages::const_iterator p
= this->packages_
.begin();
2412 p
!= this->packages_
.end();
2415 if (p
->second
!= this->package_
)
2417 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2423 // Add a type to verify. This is used for types of sink variables, in
2424 // order to give appropriate error messages.
2427 Gogo::add_type_to_verify(Type
* type
)
2429 this->verify_types_
.push_back(type
);
2432 // Traversal class used to verify types.
2434 class Verify_types
: public Traverse
2438 : Traverse(traverse_types
)
2445 // Verify that a type is correct.
2448 Verify_types::type(Type
* t
)
2451 return TRAVERSE_SKIP_COMPONENTS
;
2452 return TRAVERSE_CONTINUE
;
2455 // Verify that all types are correct.
2458 Gogo::verify_types()
2460 Verify_types traverse
;
2461 this->traverse(&traverse
);
2463 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2464 p
!= this->verify_types_
.end();
2467 this->verify_types_
.clear();
2470 // Traversal class used to lower parse tree.
2472 class Lower_parse_tree
: public Traverse
2475 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2476 : Traverse(traverse_variables
2477 | traverse_constants
2478 | traverse_functions
2479 | traverse_statements
2480 | traverse_expressions
),
2481 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2485 set_inserter(const Statement_inserter
* inserter
)
2486 { this->inserter_
= *inserter
; }
2489 variable(Named_object
*);
2492 constant(Named_object
*, bool);
2495 function(Named_object
*);
2498 statement(Block
*, size_t* pindex
, Statement
*);
2501 expression(Expression
**);
2506 // The function we are traversing.
2507 Named_object
* function_
;
2508 // Value to use for the predeclared constant iota.
2510 // Current statement inserter for use by expressions.
2511 Statement_inserter inserter_
;
2517 Lower_parse_tree::variable(Named_object
* no
)
2519 if (!no
->is_variable())
2520 return TRAVERSE_CONTINUE
;
2522 if (no
->is_variable() && no
->var_value()->is_global())
2524 // Global variables can have loops in their initialization
2525 // expressions. This is handled in lower_init_expression.
2526 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2528 return TRAVERSE_CONTINUE
;
2531 // This is a local variable. We are going to return
2532 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2533 // initialization expression when we reach the variable declaration
2534 // statement. However, that means that we need to traverse the type
2536 if (no
->var_value()->has_type())
2538 Type
* type
= no
->var_value()->type();
2541 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2542 return TRAVERSE_EXIT
;
2545 go_assert(!no
->var_value()->has_pre_init());
2547 return TRAVERSE_SKIP_COMPONENTS
;
2550 // Lower constants. We handle constants specially so that we can set
2551 // the right value for the predeclared constant iota. This works in
2552 // conjunction with the way we lower Const_expression objects.
2555 Lower_parse_tree::constant(Named_object
* no
, bool)
2557 Named_constant
* nc
= no
->const_value();
2559 // Don't get into trouble if the constant's initializer expression
2560 // refers to the constant itself.
2562 return TRAVERSE_CONTINUE
;
2565 go_assert(this->iota_value_
== -1);
2566 this->iota_value_
= nc
->iota_value();
2567 nc
->traverse_expression(this);
2568 this->iota_value_
= -1;
2570 nc
->clear_lowering();
2572 // We will traverse the expression a second time, but that will be
2575 return TRAVERSE_CONTINUE
;
2578 // Lower the body of a function, and set the closure type. Record the
2579 // function while lowering it, so that we can pass it down when
2580 // lowering an expression.
2583 Lower_parse_tree::function(Named_object
* no
)
2585 no
->func_value()->set_closure_type();
2587 go_assert(this->function_
== NULL
);
2588 this->function_
= no
;
2589 int t
= no
->func_value()->traverse(this);
2590 this->function_
= NULL
;
2592 if (t
== TRAVERSE_EXIT
)
2594 return TRAVERSE_SKIP_COMPONENTS
;
2597 // Lower statement parse trees.
2600 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
2602 // Because we explicitly traverse the statement's contents
2603 // ourselves, we want to skip block statements here. There is
2604 // nothing to lower in a block statement.
2605 if (sorig
->is_block_statement())
2606 return TRAVERSE_CONTINUE
;
2608 Statement_inserter
hold_inserter(this->inserter_
);
2609 this->inserter_
= Statement_inserter(block
, pindex
);
2611 // Lower the expressions first.
2612 int t
= sorig
->traverse_contents(this);
2613 if (t
== TRAVERSE_EXIT
)
2615 this->inserter_
= hold_inserter
;
2619 // Keep lowering until nothing changes.
2620 Statement
* s
= sorig
;
2623 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
2628 t
= s
->traverse_contents(this);
2629 if (t
== TRAVERSE_EXIT
)
2631 this->inserter_
= hold_inserter
;
2637 block
->replace_statement(*pindex
, s
);
2639 this->inserter_
= hold_inserter
;
2640 return TRAVERSE_SKIP_COMPONENTS
;
2643 // Lower expression parse trees.
2646 Lower_parse_tree::expression(Expression
** pexpr
)
2648 // We have to lower all subexpressions first, so that we can get
2649 // their type if necessary. This is awkward, because we don't have
2650 // a postorder traversal pass.
2651 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2652 return TRAVERSE_EXIT
;
2653 // Keep lowering until nothing changes.
2656 Expression
* e
= *pexpr
;
2657 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
2658 &this->inserter_
, this->iota_value_
);
2661 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2662 return TRAVERSE_EXIT
;
2665 return TRAVERSE_SKIP_COMPONENTS
;
2668 // Lower the parse tree. This is called after the parse is complete,
2669 // when all names should be resolved.
2672 Gogo::lower_parse_tree()
2674 Lower_parse_tree
lower_parse_tree(this, NULL
);
2675 this->traverse(&lower_parse_tree
);
2677 // There might be type definitions that involve expressions such as the
2678 // array length. Make sure to lower these expressions as well. Otherwise,
2679 // errors hidden within a type can introduce unexpected errors into later
2681 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2682 p
!= this->verify_types_
.end();
2684 Type::traverse(*p
, &lower_parse_tree
);
2690 Gogo::lower_block(Named_object
* function
, Block
* block
)
2692 Lower_parse_tree
lower_parse_tree(this, function
);
2693 block
->traverse(&lower_parse_tree
);
2696 // Lower an expression. INSERTER may be NULL, in which case the
2697 // expression had better not need to create any temporaries.
2700 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
2703 Lower_parse_tree
lower_parse_tree(this, function
);
2704 if (inserter
!= NULL
)
2705 lower_parse_tree
.set_inserter(inserter
);
2706 lower_parse_tree
.expression(pexpr
);
2709 // Lower a constant. This is called when lowering a reference to a
2710 // constant. We have to make sure that the constant has already been
2714 Gogo::lower_constant(Named_object
* no
)
2716 go_assert(no
->is_const());
2717 Lower_parse_tree
lower(this, NULL
);
2718 lower
.constant(no
, false);
2721 // Traverse the tree to create function descriptors as needed.
2723 class Create_function_descriptors
: public Traverse
2726 Create_function_descriptors(Gogo
* gogo
)
2727 : Traverse(traverse_functions
| traverse_expressions
),
2732 function(Named_object
*);
2735 expression(Expression
**);
2741 // Create a descriptor for every top-level exported function.
2744 Create_function_descriptors::function(Named_object
* no
)
2746 if (no
->is_function()
2747 && no
->func_value()->enclosing() == NULL
2748 && !no
->func_value()->is_method()
2749 && !Gogo::is_hidden_name(no
->name())
2750 && !Gogo::is_thunk(no
))
2751 no
->func_value()->descriptor(this->gogo_
, no
);
2753 return TRAVERSE_CONTINUE
;
2756 // If we see a function referenced in any way other than calling it,
2757 // create a descriptor for it.
2760 Create_function_descriptors::expression(Expression
** pexpr
)
2762 Expression
* expr
= *pexpr
;
2764 Func_expression
* fe
= expr
->func_expression();
2767 // We would not get here for a call to this function, so this is
2768 // a reference to a function other than calling it. We need a
2770 if (fe
->closure() != NULL
)
2771 return TRAVERSE_CONTINUE
;
2772 Named_object
* no
= fe
->named_object();
2773 if (no
->is_function() && !no
->func_value()->is_method())
2774 no
->func_value()->descriptor(this->gogo_
, no
);
2775 else if (no
->is_function_declaration()
2776 && !no
->func_declaration_value()->type()->is_method()
2777 && !Linemap::is_predeclared_location(no
->location()))
2778 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
2779 return TRAVERSE_CONTINUE
;
2782 Bound_method_expression
* bme
= expr
->bound_method_expression();
2785 // We would not get here for a call to this method, so this is a
2786 // method value. We need to create a thunk.
2787 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
2789 return TRAVERSE_CONTINUE
;
2792 Interface_field_reference_expression
* ifre
=
2793 expr
->interface_field_reference_expression();
2796 // We would not get here for a call to this interface method, so
2797 // this is a method value. We need to create a thunk.
2798 Interface_type
* type
= ifre
->expr()->type()->interface_type();
2800 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
2802 return TRAVERSE_CONTINUE
;
2805 Call_expression
* ce
= expr
->call_expression();
2808 Expression
* fn
= ce
->fn();
2809 if (fn
->func_expression() != NULL
2810 || fn
->bound_method_expression() != NULL
2811 || fn
->interface_field_reference_expression() != NULL
)
2813 // Traverse the arguments but not the function.
2814 Expression_list
* args
= ce
->args();
2817 if (args
->traverse(this) == TRAVERSE_EXIT
)
2818 return TRAVERSE_EXIT
;
2820 return TRAVERSE_SKIP_COMPONENTS
;
2824 return TRAVERSE_CONTINUE
;
2827 // Create function descriptors as needed. We need a function
2828 // descriptor for all exported functions and for all functions that
2829 // are referenced without being called.
2832 Gogo::create_function_descriptors()
2834 // Create a function descriptor for any exported function that is
2835 // declared in this package. This is so that we have a descriptor
2836 // for functions written in assembly. Gather the descriptors first
2837 // so that we don't add declarations while looping over them.
2838 std::vector
<Named_object
*> fndecls
;
2839 Bindings
* b
= this->package_
->bindings();
2840 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
2841 p
!= b
->end_declarations();
2844 Named_object
* no
= p
->second
;
2845 if (no
->is_function_declaration()
2846 && !no
->func_declaration_value()->type()->is_method()
2847 && !Linemap::is_predeclared_location(no
->location())
2848 && !Gogo::is_hidden_name(no
->name()))
2849 fndecls
.push_back(no
);
2851 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
2854 (*p
)->func_declaration_value()->descriptor(this, *p
);
2857 Create_function_descriptors
cfd(this);
2858 this->traverse(&cfd
);
2861 // Look for interface types to finalize methods of inherited
2864 class Finalize_methods
: public Traverse
2867 Finalize_methods(Gogo
* gogo
)
2868 : Traverse(traverse_types
),
2879 // Finalize the methods of an interface type.
2882 Finalize_methods::type(Type
* t
)
2884 // Check the classification so that we don't finalize the methods
2885 // twice for a named interface type.
2886 switch (t
->classification())
2888 case Type::TYPE_INTERFACE
:
2889 t
->interface_type()->finalize_methods();
2892 case Type::TYPE_NAMED
:
2894 // We have to finalize the methods of the real type first.
2895 // But if the real type is a struct type, then we only want to
2896 // finalize the methods of the field types, not of the struct
2897 // type itself. We don't want to add methods to the struct,
2898 // since it has a name.
2899 Named_type
* nt
= t
->named_type();
2900 Type
* rt
= nt
->real_type();
2901 if (rt
->classification() != Type::TYPE_STRUCT
)
2903 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2904 return TRAVERSE_EXIT
;
2908 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
2909 return TRAVERSE_EXIT
;
2912 nt
->finalize_methods(this->gogo_
);
2914 // If this type is defined in a different package, then finalize the
2915 // types of all the methods, since we won't see them otherwise.
2916 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
2918 const Methods
* methods
= nt
->methods();
2919 for (Methods::const_iterator p
= methods
->begin();
2920 p
!= methods
->end();
2923 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
2924 return TRAVERSE_EXIT
;
2928 // Finalize the types of all methods that are declared but not
2929 // defined, since we won't see the declarations otherwise.
2930 if (nt
->named_object()->package() == NULL
2931 && nt
->local_methods() != NULL
)
2933 const Bindings
* methods
= nt
->local_methods();
2934 for (Bindings::const_declarations_iterator p
=
2935 methods
->begin_declarations();
2936 p
!= methods
->end_declarations();
2939 if (p
->second
->is_function_declaration())
2941 Type
* mt
= p
->second
->func_declaration_value()->type();
2942 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
2943 return TRAVERSE_EXIT
;
2948 return TRAVERSE_SKIP_COMPONENTS
;
2951 case Type::TYPE_STRUCT
:
2952 // Traverse the field types first in case there is an embedded
2953 // field with methods that the struct should inherit.
2954 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
2955 return TRAVERSE_EXIT
;
2956 t
->struct_type()->finalize_methods(this->gogo_
);
2957 return TRAVERSE_SKIP_COMPONENTS
;
2963 return TRAVERSE_CONTINUE
;
2966 // Finalize method lists and build stub methods for types.
2969 Gogo::finalize_methods()
2971 Finalize_methods
finalize(this);
2972 this->traverse(&finalize
);
2975 // Set types for unspecified variables and constants.
2978 Gogo::determine_types()
2980 Bindings
* bindings
= this->current_bindings();
2981 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
2982 p
!= bindings
->end_definitions();
2985 if ((*p
)->is_function())
2986 (*p
)->func_value()->determine_types();
2987 else if ((*p
)->is_variable())
2988 (*p
)->var_value()->determine_type();
2989 else if ((*p
)->is_const())
2990 (*p
)->const_value()->determine_type();
2992 // See if a variable requires us to build an initialization
2993 // function. We know that we will see all global variables
2995 if (!this->need_init_fn_
&& (*p
)->is_variable())
2997 Variable
* variable
= (*p
)->var_value();
2999 // If this is a global variable which requires runtime
3000 // initialization, we need an initialization function.
3001 if (!variable
->is_global())
3003 else if (variable
->init() == NULL
)
3005 else if (variable
->type()->interface_type() != NULL
)
3006 this->need_init_fn_
= true;
3007 else if (variable
->init()->is_constant())
3009 else if (!variable
->init()->is_composite_literal())
3010 this->need_init_fn_
= true;
3011 else if (variable
->init()->is_nonconstant_composite_literal())
3012 this->need_init_fn_
= true;
3014 // If this is a global variable which holds a pointer value,
3015 // then we need an initialization function to register it as a
3017 if (variable
->is_global() && variable
->type()->has_pointer())
3018 this->need_init_fn_
= true;
3022 // Determine the types of constants in packages.
3023 for (Packages::const_iterator p
= this->packages_
.begin();
3024 p
!= this->packages_
.end();
3026 p
->second
->determine_types();
3029 // Traversal class used for type checking.
3031 class Check_types_traverse
: public Traverse
3034 Check_types_traverse(Gogo
* gogo
)
3035 : Traverse(traverse_variables
3036 | traverse_constants
3037 | traverse_functions
3038 | traverse_statements
3039 | traverse_expressions
),
3044 variable(Named_object
*);
3047 constant(Named_object
*, bool);
3050 function(Named_object
*);
3053 statement(Block
*, size_t* pindex
, Statement
*);
3056 expression(Expression
**);
3063 // Check that a variable initializer has the right type.
3066 Check_types_traverse::variable(Named_object
* named_object
)
3068 if (named_object
->is_variable())
3070 Variable
* var
= named_object
->var_value();
3072 // Give error if variable type is not defined.
3073 var
->type()->base();
3075 Expression
* init
= var
->init();
3078 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3081 error_at(var
->location(), "incompatible type in initialization");
3083 error_at(var
->location(),
3084 "incompatible type in initialization (%s)",
3086 init
= Expression::make_error(named_object
->location());
3089 else if (init
!= NULL
3090 && init
->func_expression() != NULL
)
3092 Named_object
* no
= init
->func_expression()->named_object();
3093 Function_type
* fntype
;
3094 if (no
->is_function())
3095 fntype
= no
->func_value()->type();
3096 else if (no
->is_function_declaration())
3097 fntype
= no
->func_declaration_value()->type();
3101 // Builtin functions cannot be used as function values for variable
3103 if (fntype
->is_builtin())
3105 error_at(init
->location(),
3106 "invalid use of special builtin function %qs; "
3108 no
->message_name().c_str());
3112 && !var
->is_global()
3113 && !var
->is_parameter()
3114 && !var
->is_receiver()
3115 && !var
->type()->is_error()
3116 && (init
== NULL
|| !init
->is_error_expression())
3117 && !Lex::is_invalid_identifier(named_object
->name()))
3118 error_at(var
->location(), "%qs declared and not used",
3119 named_object
->message_name().c_str());
3121 return TRAVERSE_CONTINUE
;
3124 // Check that a constant initializer has the right type.
3127 Check_types_traverse::constant(Named_object
* named_object
, bool)
3129 Named_constant
* constant
= named_object
->const_value();
3130 Type
* ctype
= constant
->type();
3131 if (ctype
->integer_type() == NULL
3132 && ctype
->float_type() == NULL
3133 && ctype
->complex_type() == NULL
3134 && !ctype
->is_boolean_type()
3135 && !ctype
->is_string_type())
3137 if (ctype
->is_nil_type())
3138 error_at(constant
->location(), "const initializer cannot be nil");
3139 else if (!ctype
->is_error())
3140 error_at(constant
->location(), "invalid constant type");
3141 constant
->set_error();
3143 else if (!constant
->expr()->is_constant())
3145 error_at(constant
->expr()->location(), "expression is not constant");
3146 constant
->set_error();
3148 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3151 error_at(constant
->location(),
3152 "initialization expression has wrong type");
3153 constant
->set_error();
3155 return TRAVERSE_CONTINUE
;
3158 // There are no types to check in a function, but this is where we
3159 // issue warnings about labels which are defined but not referenced.
3162 Check_types_traverse::function(Named_object
* no
)
3164 no
->func_value()->check_labels();
3165 return TRAVERSE_CONTINUE
;
3168 // Check that types are valid in a statement.
3171 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3173 s
->check_types(this->gogo_
);
3174 return TRAVERSE_CONTINUE
;
3177 // Check that types are valid in an expression.
3180 Check_types_traverse::expression(Expression
** expr
)
3182 (*expr
)->check_types(this->gogo_
);
3183 return TRAVERSE_CONTINUE
;
3186 // Check that types are valid.
3191 Check_types_traverse
traverse(this);
3192 this->traverse(&traverse
);
3194 Bindings
* bindings
= this->current_bindings();
3195 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3196 p
!= bindings
->end_declarations();
3199 // Also check the types in a function declaration's signature.
3200 Named_object
* no
= p
->second
;
3201 if (no
->is_function_declaration())
3202 no
->func_declaration_value()->check_types();
3206 // Check the types in a single block.
3209 Gogo::check_types_in_block(Block
* block
)
3211 Check_types_traverse
traverse(this);
3212 block
->traverse(&traverse
);
3215 // A traversal class used to find a single shortcut operator within an
3218 class Find_shortcut
: public Traverse
3222 : Traverse(traverse_blocks
3223 | traverse_statements
3224 | traverse_expressions
),
3228 // A pointer to the expression which was found, or NULL if none was
3232 { return this->found_
; }
3237 { return TRAVERSE_SKIP_COMPONENTS
; }
3240 statement(Block
*, size_t*, Statement
*)
3241 { return TRAVERSE_SKIP_COMPONENTS
; }
3244 expression(Expression
**);
3247 Expression
** found_
;
3250 // Find a shortcut expression.
3253 Find_shortcut::expression(Expression
** pexpr
)
3255 Expression
* expr
= *pexpr
;
3256 Binary_expression
* be
= expr
->binary_expression();
3258 return TRAVERSE_CONTINUE
;
3259 Operator op
= be
->op();
3260 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
3261 return TRAVERSE_CONTINUE
;
3262 go_assert(this->found_
== NULL
);
3263 this->found_
= pexpr
;
3264 return TRAVERSE_EXIT
;
3267 // A traversal class used to turn shortcut operators into explicit if
3270 class Shortcuts
: public Traverse
3273 Shortcuts(Gogo
* gogo
)
3274 : Traverse(traverse_variables
3275 | traverse_statements
),
3281 variable(Named_object
*);
3284 statement(Block
*, size_t*, Statement
*);
3287 // Convert a shortcut operator.
3289 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
3295 // Remove shortcut operators in a single statement.
3298 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3300 // FIXME: This approach doesn't work for switch statements, because
3301 // we add the new statements before the whole switch when we need to
3302 // instead add them just before the switch expression. The right
3303 // fix is probably to lower switch statements with nonconstant cases
3304 // to a series of conditionals.
3305 if (s
->switch_statement() != NULL
)
3306 return TRAVERSE_CONTINUE
;
3310 Find_shortcut find_shortcut
;
3312 // If S is a variable declaration, then ordinary traversal won't
3313 // do anything. We want to explicitly traverse the
3314 // initialization expression if there is one.
3315 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3316 Expression
* init
= NULL
;
3318 s
->traverse_contents(&find_shortcut
);
3321 init
= vds
->var()->var_value()->init();
3323 return TRAVERSE_CONTINUE
;
3324 init
->traverse(&init
, &find_shortcut
);
3326 Expression
** pshortcut
= find_shortcut
.found();
3327 if (pshortcut
== NULL
)
3328 return TRAVERSE_CONTINUE
;
3330 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
3331 block
->insert_statement_before(*pindex
, snew
);
3334 if (pshortcut
== &init
)
3335 vds
->var()->var_value()->set_init(init
);
3339 // Remove shortcut operators in the initializer of a global variable.
3342 Shortcuts::variable(Named_object
* no
)
3344 if (no
->is_result_variable())
3345 return TRAVERSE_CONTINUE
;
3346 Variable
* var
= no
->var_value();
3347 Expression
* init
= var
->init();
3348 if (!var
->is_global() || init
== NULL
)
3349 return TRAVERSE_CONTINUE
;
3353 Find_shortcut find_shortcut
;
3354 init
->traverse(&init
, &find_shortcut
);
3355 Expression
** pshortcut
= find_shortcut
.found();
3356 if (pshortcut
== NULL
)
3357 return TRAVERSE_CONTINUE
;
3359 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
3360 var
->add_preinit_statement(this->gogo_
, snew
);
3361 if (pshortcut
== &init
)
3362 var
->set_init(init
);
3366 // Given an expression which uses a shortcut operator, return a
3367 // statement which implements it, and update *PSHORTCUT accordingly.
3370 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
3372 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
3373 Expression
* left
= shortcut
->left();
3374 Expression
* right
= shortcut
->right();
3375 Location loc
= shortcut
->location();
3377 Block
* retblock
= new Block(enclosing
, loc
);
3378 retblock
->set_end_location(loc
);
3380 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
3382 retblock
->add_statement(ts
);
3384 Block
* block
= new Block(retblock
, loc
);
3385 block
->set_end_location(loc
);
3386 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
3387 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
3388 block
->add_statement(assign
);
3390 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
3391 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
3392 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
3394 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
3396 retblock
->add_statement(if_statement
);
3398 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
3402 // Now convert any shortcut operators in LEFT and RIGHT.
3403 Shortcuts
shortcuts(this->gogo_
);
3404 retblock
->traverse(&shortcuts
);
3406 return Statement::make_block_statement(retblock
, loc
);
3409 // Turn shortcut operators into explicit if statements. Doing this
3410 // considerably simplifies the order of evaluation rules.
3413 Gogo::remove_shortcuts()
3415 Shortcuts
shortcuts(this);
3416 this->traverse(&shortcuts
);
3419 // A traversal class which finds all the expressions which must be
3420 // evaluated in order within a statement or larger expression. This
3421 // is used to implement the rules about order of evaluation.
3423 class Find_eval_ordering
: public Traverse
3426 typedef std::vector
<Expression
**> Expression_pointers
;
3429 Find_eval_ordering()
3430 : Traverse(traverse_blocks
3431 | traverse_statements
3432 | traverse_expressions
),
3438 { return this->exprs_
.size(); }
3440 typedef Expression_pointers::const_iterator const_iterator
;
3444 { return this->exprs_
.begin(); }
3448 { return this->exprs_
.end(); }
3453 { return TRAVERSE_SKIP_COMPONENTS
; }
3456 statement(Block
*, size_t*, Statement
*)
3457 { return TRAVERSE_SKIP_COMPONENTS
; }
3460 expression(Expression
**);
3463 // A list of pointers to expressions with side-effects.
3464 Expression_pointers exprs_
;
3467 // If an expression must be evaluated in order, put it on the list.
3470 Find_eval_ordering::expression(Expression
** expression_pointer
)
3472 // We have to look at subexpressions before this one.
3473 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3474 return TRAVERSE_EXIT
;
3475 if ((*expression_pointer
)->must_eval_in_order())
3476 this->exprs_
.push_back(expression_pointer
);
3477 return TRAVERSE_SKIP_COMPONENTS
;
3480 // A traversal class for ordering evaluations.
3482 class Order_eval
: public Traverse
3485 Order_eval(Gogo
* gogo
)
3486 : Traverse(traverse_variables
3487 | traverse_statements
),
3492 variable(Named_object
*);
3495 statement(Block
*, size_t*, Statement
*);
3502 // Implement the order of evaluation rules for a statement.
3505 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3507 // FIXME: This approach doesn't work for switch statements, because
3508 // we add the new statements before the whole switch when we need to
3509 // instead add them just before the switch expression. The right
3510 // fix is probably to lower switch statements with nonconstant cases
3511 // to a series of conditionals.
3512 if (s
->switch_statement() != NULL
)
3513 return TRAVERSE_CONTINUE
;
3515 Find_eval_ordering find_eval_ordering
;
3517 // If S is a variable declaration, then ordinary traversal won't do
3518 // anything. We want to explicitly traverse the initialization
3519 // expression if there is one.
3520 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3521 Expression
* init
= NULL
;
3522 Expression
* orig_init
= NULL
;
3524 s
->traverse_contents(&find_eval_ordering
);
3527 init
= vds
->var()->var_value()->init();
3529 return TRAVERSE_CONTINUE
;
3532 // It might seem that this could be
3533 // init->traverse_subexpressions. Unfortunately that can fail
3536 // newvar, err := call(arg())
3537 // Here newvar will have an init of call result 0 of
3538 // call(arg()). If we only traverse subexpressions, we will
3539 // only find arg(), and we won't bother to move anything out.
3540 // Then we get to the assignment to err, we will traverse the
3541 // whole statement, and this time we will find both call() and
3542 // arg(), and so we will move them out. This will cause them to
3543 // be put into temporary variables before the assignment to err
3544 // but after the declaration of newvar. To avoid that problem,
3545 // we traverse the entire expression here.
3546 Expression::traverse(&init
, &find_eval_ordering
);
3549 size_t c
= find_eval_ordering
.size();
3551 return TRAVERSE_CONTINUE
;
3553 // If there is only one expression with a side-effect, we can
3554 // usually leave it in place.
3557 switch (s
->classification())
3559 case Statement::STATEMENT_ASSIGNMENT
:
3560 // For an assignment statement, we need to evaluate an
3561 // expression on the right hand side before we evaluate any
3562 // index expression on the left hand side, so for that case
3563 // we always move the expression. Otherwise we mishandle
3564 // m[0] = len(m) where m is a map.
3567 case Statement::STATEMENT_EXPRESSION
:
3569 // If this is a call statement that doesn't return any
3570 // values, it will not have been counted as a value to
3571 // move. We need to move any subexpressions in case they
3572 // are themselves call statements that require passing a
3574 Expression
* expr
= s
->expression_statement()->expr();
3575 if (expr
->call_expression() != NULL
3576 && expr
->call_expression()->result_count() == 0)
3578 return TRAVERSE_CONTINUE
;
3582 // We can leave the expression in place.
3583 return TRAVERSE_CONTINUE
;
3587 bool is_thunk
= s
->thunk_statement() != NULL
;
3588 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3589 p
!= find_eval_ordering
.end();
3592 Expression
** pexpr
= *p
;
3594 // The last expression in a thunk will be the call passed to go
3595 // or defer, which we must not evaluate early.
3596 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
3599 Location loc
= (*pexpr
)->location();
3601 if ((*pexpr
)->call_expression() == NULL
3602 || (*pexpr
)->call_expression()->result_count() < 2)
3604 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3607 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3611 // A call expression which returns multiple results needs to
3612 // be handled specially. We can't create a temporary
3613 // because there is no type to give it. Any actual uses of
3614 // the values will be done via Call_result_expressions.
3615 s
= Statement::make_statement(*pexpr
, true);
3618 block
->insert_statement_before(*pindex
, s
);
3622 if (init
!= orig_init
)
3623 vds
->var()->var_value()->set_init(init
);
3625 return TRAVERSE_CONTINUE
;
3628 // Implement the order of evaluation rules for the initializer of a
3632 Order_eval::variable(Named_object
* no
)
3634 if (no
->is_result_variable())
3635 return TRAVERSE_CONTINUE
;
3636 Variable
* var
= no
->var_value();
3637 Expression
* init
= var
->init();
3638 if (!var
->is_global() || init
== NULL
)
3639 return TRAVERSE_CONTINUE
;
3641 Find_eval_ordering find_eval_ordering
;
3642 Expression::traverse(&init
, &find_eval_ordering
);
3644 if (find_eval_ordering
.size() <= 1)
3646 // If there is only one expression with a side-effect, we can
3647 // leave it in place.
3648 return TRAVERSE_SKIP_COMPONENTS
;
3651 Expression
* orig_init
= init
;
3653 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3654 p
!= find_eval_ordering
.end();
3657 Expression
** pexpr
= *p
;
3658 Location loc
= (*pexpr
)->location();
3660 if ((*pexpr
)->call_expression() == NULL
3661 || (*pexpr
)->call_expression()->result_count() < 2)
3663 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3666 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3670 // A call expression which returns multiple results needs to
3671 // be handled specially.
3672 s
= Statement::make_statement(*pexpr
, true);
3674 var
->add_preinit_statement(this->gogo_
, s
);
3677 if (init
!= orig_init
)
3678 var
->set_init(init
);
3680 return TRAVERSE_SKIP_COMPONENTS
;
3683 // Use temporary variables to implement the order of evaluation rules.
3686 Gogo::order_evaluations()
3688 Order_eval
order_eval(this);
3689 this->traverse(&order_eval
);
3692 // Traversal to flatten parse tree after order of evaluation rules are applied.
3694 class Flatten
: public Traverse
3697 Flatten(Gogo
* gogo
, Named_object
* function
)
3698 : Traverse(traverse_variables
3699 | traverse_functions
3700 | traverse_statements
3701 | traverse_expressions
),
3702 gogo_(gogo
), function_(function
), inserter_()
3706 set_inserter(const Statement_inserter
* inserter
)
3707 { this->inserter_
= *inserter
; }
3710 variable(Named_object
*);
3713 function(Named_object
*);
3716 statement(Block
*, size_t* pindex
, Statement
*);
3719 expression(Expression
**);
3724 // The function we are traversing.
3725 Named_object
* function_
;
3726 // Current statement inserter for use by expressions.
3727 Statement_inserter inserter_
;
3730 // Flatten variables.
3733 Flatten::variable(Named_object
* no
)
3735 if (!no
->is_variable())
3736 return TRAVERSE_CONTINUE
;
3738 if (no
->is_variable() && no
->var_value()->is_global())
3740 // Global variables can have loops in their initialization
3741 // expressions. This is handled in flatten_init_expression.
3742 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
3744 return TRAVERSE_CONTINUE
;
3747 go_assert(!no
->var_value()->has_pre_init());
3749 return TRAVERSE_SKIP_COMPONENTS
;
3752 // Flatten the body of a function. Record the function while flattening it,
3753 // so that we can pass it down when flattening an expression.
3756 Flatten::function(Named_object
* no
)
3758 go_assert(this->function_
== NULL
);
3759 this->function_
= no
;
3760 int t
= no
->func_value()->traverse(this);
3761 this->function_
= NULL
;
3763 if (t
== TRAVERSE_EXIT
)
3765 return TRAVERSE_SKIP_COMPONENTS
;
3768 // Flatten statement parse trees.
3771 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3773 // Because we explicitly traverse the statement's contents
3774 // ourselves, we want to skip block statements here. There is
3775 // nothing to flatten in a block statement.
3776 if (sorig
->is_block_statement())
3777 return TRAVERSE_CONTINUE
;
3779 Statement_inserter
hold_inserter(this->inserter_
);
3780 this->inserter_
= Statement_inserter(block
, pindex
);
3782 // Flatten the expressions first.
3783 int t
= sorig
->traverse_contents(this);
3784 if (t
== TRAVERSE_EXIT
)
3786 this->inserter_
= hold_inserter
;
3790 // Keep flattening until nothing changes.
3791 Statement
* s
= sorig
;
3794 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
3799 t
= s
->traverse_contents(this);
3800 if (t
== TRAVERSE_EXIT
)
3802 this->inserter_
= hold_inserter
;
3808 block
->replace_statement(*pindex
, s
);
3810 this->inserter_
= hold_inserter
;
3811 return TRAVERSE_SKIP_COMPONENTS
;
3814 // Flatten expression parse trees.
3817 Flatten::expression(Expression
** pexpr
)
3819 // Keep flattening until nothing changes.
3822 Expression
* e
= *pexpr
;
3823 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3824 return TRAVERSE_EXIT
;
3826 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
3832 return TRAVERSE_SKIP_COMPONENTS
;
3838 Gogo::flatten_block(Named_object
* function
, Block
* block
)
3840 Flatten
flatten(this, function
);
3841 block
->traverse(&flatten
);
3844 // Flatten an expression. INSERTER may be NULL, in which case the
3845 // expression had better not need to create any temporaries.
3848 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
3851 Flatten
flatten(this, function
);
3852 if (inserter
!= NULL
)
3853 flatten
.set_inserter(inserter
);
3854 flatten
.expression(pexpr
);
3860 Flatten
flatten(this, NULL
);
3861 this->traverse(&flatten
);
3864 // Traversal to convert calls to the predeclared recover function to
3865 // pass in an argument indicating whether it can recover from a panic
3868 class Convert_recover
: public Traverse
3871 Convert_recover(Named_object
* arg
)
3872 : Traverse(traverse_expressions
),
3878 expression(Expression
**);
3881 // The argument to pass to the function.
3885 // Convert calls to recover.
3888 Convert_recover::expression(Expression
** pp
)
3890 Call_expression
* ce
= (*pp
)->call_expression();
3891 if (ce
!= NULL
&& ce
->is_recover_call())
3892 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
3894 return TRAVERSE_CONTINUE
;
3897 // Traversal for build_recover_thunks.
3899 class Build_recover_thunks
: public Traverse
3902 Build_recover_thunks(Gogo
* gogo
)
3903 : Traverse(traverse_functions
),
3908 function(Named_object
*);
3912 can_recover_arg(Location
);
3918 // If this function calls recover, turn it into a thunk.
3921 Build_recover_thunks::function(Named_object
* orig_no
)
3923 Function
* orig_func
= orig_no
->func_value();
3924 if (!orig_func
->calls_recover()
3925 || orig_func
->is_recover_thunk()
3926 || orig_func
->has_recover_thunk())
3927 return TRAVERSE_CONTINUE
;
3929 Gogo
* gogo
= this->gogo_
;
3930 Location location
= orig_func
->location();
3935 Function_type
* orig_fntype
= orig_func
->type();
3936 Typed_identifier_list
* new_params
= new Typed_identifier_list();
3937 std::string receiver_name
;
3938 if (orig_fntype
->is_method())
3940 const Typed_identifier
* receiver
= orig_fntype
->receiver();
3941 snprintf(buf
, sizeof buf
, "rt.%u", count
);
3943 receiver_name
= buf
;
3944 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
3945 receiver
->location()));
3947 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
3948 if (orig_params
!= NULL
&& !orig_params
->empty())
3950 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
3951 p
!= orig_params
->end();
3954 snprintf(buf
, sizeof buf
, "pt.%u", count
);
3956 new_params
->push_back(Typed_identifier(buf
, p
->type(),
3960 snprintf(buf
, sizeof buf
, "pr.%u", count
);
3962 std::string can_recover_name
= buf
;
3963 new_params
->push_back(Typed_identifier(can_recover_name
,
3964 Type::lookup_bool_type(),
3965 orig_fntype
->location()));
3967 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
3968 Typed_identifier_list
* new_results
;
3969 if (orig_results
== NULL
|| orig_results
->empty())
3973 new_results
= new Typed_identifier_list();
3974 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
3975 p
!= orig_results
->end();
3977 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
3980 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
3982 orig_fntype
->location());
3983 if (orig_fntype
->is_varargs())
3984 new_fntype
->set_is_varargs();
3986 std::string name
= orig_no
->name();
3987 if (orig_fntype
->is_method())
3988 name
+= "$" + orig_fntype
->receiver()->type()->mangled_name(gogo
);
3990 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
3992 Function
*new_func
= new_no
->func_value();
3993 if (orig_func
->enclosing() != NULL
)
3994 new_func
->set_enclosing(orig_func
->enclosing());
3996 // We build the code for the original function attached to the new
3997 // function, and then swap the original and new function bodies.
3998 // This means that existing references to the original function will
3999 // then refer to the new function. That makes this code a little
4000 // confusing, in that the reference to NEW_NO really refers to the
4001 // other function, not the one we are building.
4003 Expression
* closure
= NULL
;
4004 if (orig_func
->needs_closure())
4006 // For the new function we are creating, declare a new parameter
4007 // variable NEW_CLOSURE_NO and set it to be the closure variable
4008 // of the function. This will be set to the closure value
4009 // passed in by the caller. Then pass a reference to this
4010 // variable as the closure value when calling the original
4011 // function. In other words, simply pass the closure value
4012 // through the thunk we are creating.
4013 Named_object
* orig_closure_no
= orig_func
->closure_var();
4014 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4015 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4016 false, false, location
);
4017 new_var
->set_is_closure();
4018 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4020 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4022 new_func
->set_closure_var(new_closure_no
);
4023 closure
= Expression::make_var_reference(new_closure_no
, location
);
4026 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4028 Expression_list
* args
= new Expression_list();
4029 if (new_params
!= NULL
)
4031 // Note that we skip the last parameter, which is the boolean
4032 // indicating whether recover can succed.
4033 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4034 p
+ 1 != new_params
->end();
4037 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4038 go_assert(p_no
!= NULL
4039 && p_no
->is_variable()
4040 && p_no
->var_value()->is_parameter());
4041 args
->push_back(Expression::make_var_reference(p_no
, location
));
4044 args
->push_back(this->can_recover_arg(location
));
4046 gogo
->start_block(location
);
4048 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4050 // Any varargs call has already been lowered.
4051 call
->set_varargs_are_lowered();
4053 Statement
* s
= Statement::make_return_from_call(call
, location
);
4054 s
->determine_types();
4055 gogo
->add_statement(s
);
4057 Block
* b
= gogo
->finish_block(location
);
4059 gogo
->add_block(b
, location
);
4061 // Lower the call in case it returns multiple results.
4062 gogo
->lower_block(new_no
, b
);
4064 gogo
->finish_function(location
);
4066 // Swap the function bodies and types.
4067 new_func
->swap_for_recover(orig_func
);
4068 orig_func
->set_is_recover_thunk();
4069 new_func
->set_calls_recover();
4070 new_func
->set_has_recover_thunk();
4072 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4073 Bindings
* new_bindings
= new_func
->block()->bindings();
4074 if (orig_fntype
->is_method())
4076 // We changed the receiver to be a regular parameter. We have
4077 // to update the binding accordingly in both functions.
4078 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4079 go_assert(orig_rec_no
!= NULL
4080 && orig_rec_no
->is_variable()
4081 && !orig_rec_no
->var_value()->is_receiver());
4082 orig_rec_no
->var_value()->set_is_receiver();
4084 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4085 if (new_receiver_name
.empty())
4087 // Find the receiver. It was named "r.NNN" in
4088 // Gogo::start_function.
4089 for (Bindings::const_definitions_iterator p
=
4090 new_bindings
->begin_definitions();
4091 p
!= new_bindings
->end_definitions();
4094 const std::string
& pname((*p
)->name());
4095 if (pname
[0] == 'r' && pname
[1] == '.')
4097 new_receiver_name
= pname
;
4101 go_assert(!new_receiver_name
.empty());
4103 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4104 if (new_rec_no
== NULL
)
4105 go_assert(saw_errors());
4108 go_assert(new_rec_no
->is_variable()
4109 && new_rec_no
->var_value()->is_receiver());
4110 new_rec_no
->var_value()->set_is_not_receiver();
4114 // Because we flipped blocks but not types, the can_recover
4115 // parameter appears in the (now) old bindings as a parameter.
4116 // Change it to a local variable, whereupon it will be discarded.
4117 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4118 go_assert(can_recover_no
!= NULL
4119 && can_recover_no
->is_variable()
4120 && can_recover_no
->var_value()->is_parameter());
4121 orig_bindings
->remove_binding(can_recover_no
);
4123 // Add the can_recover argument to the (now) new bindings, and
4124 // attach it to any recover statements.
4125 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4126 false, true, false, location
);
4127 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4129 Convert_recover
convert_recover(can_recover_no
);
4130 new_func
->traverse(&convert_recover
);
4132 // Update the function pointers in any named results.
4133 new_func
->update_result_variables();
4134 orig_func
->update_result_variables();
4136 return TRAVERSE_CONTINUE
;
4139 // Return the expression to pass for the .can_recover parameter to the
4140 // new function. This indicates whether a call to recover may return
4141 // non-nil. The expression is
4142 // __go_can_recover(__builtin_return_address()).
4145 Build_recover_thunks::can_recover_arg(Location location
)
4147 static Named_object
* builtin_return_address
;
4148 if (builtin_return_address
== NULL
)
4150 const Location bloc
= Linemap::predeclared_location();
4152 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4153 Type
* uint_type
= Type::lookup_integer_type("uint");
4154 param_types
->push_back(Typed_identifier("l", uint_type
, bloc
));
4156 Typed_identifier_list
* return_types
= new Typed_identifier_list();
4157 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4158 return_types
->push_back(Typed_identifier("", voidptr_type
, bloc
));
4160 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4161 return_types
, bloc
);
4162 builtin_return_address
=
4163 Named_object::make_function_declaration("__builtin_return_address",
4164 NULL
, fntype
, bloc
);
4165 const char* n
= "__builtin_return_address";
4166 builtin_return_address
->func_declaration_value()->set_asm_name(n
);
4169 static Named_object
* can_recover
;
4170 if (can_recover
== NULL
)
4172 const Location bloc
= Linemap::predeclared_location();
4173 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4174 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4175 param_types
->push_back(Typed_identifier("a", voidptr_type
, bloc
));
4176 Type
* boolean_type
= Type::lookup_bool_type();
4177 Typed_identifier_list
* results
= new Typed_identifier_list();
4178 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4179 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4181 can_recover
= Named_object::make_function_declaration("__go_can_recover",
4184 can_recover
->func_declaration_value()->set_asm_name("__go_can_recover");
4187 Expression
* fn
= Expression::make_func_reference(builtin_return_address
,
4190 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4191 Expression_list
*args
= new Expression_list();
4192 args
->push_back(zexpr
);
4194 Expression
* call
= Expression::make_call(fn
, args
, false, location
);
4196 args
= new Expression_list();
4197 args
->push_back(call
);
4199 fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4200 return Expression::make_call(fn
, args
, false, location
);
4203 // Build thunks for functions which call recover. We build a new
4204 // function with an extra parameter, which is whether a call to
4205 // recover can succeed. We then move the body of this function to
4206 // that one. We then turn this function into a thunk which calls the
4207 // new one, passing the value of
4208 // __go_can_recover(__builtin_return_address()). The function will be
4209 // marked as not splitting the stack. This will cooperate with the
4210 // implementation of defer to make recover do the right thing.
4213 Gogo::build_recover_thunks()
4215 Build_recover_thunks
build_recover_thunks(this);
4216 this->traverse(&build_recover_thunks
);
4219 // Build a call to the runtime error function.
4222 Gogo::runtime_error(int code
, Location location
)
4224 Type
* int32_type
= Type::lookup_integer_type("int32");
4225 Expression
* code_expr
= Expression::make_integer_ul(code
, int32_type
,
4227 return Runtime::make_call(Runtime::RUNTIME_ERROR
, location
, 1, code_expr
);
4230 // Look for named types to see whether we need to create an interface
4233 class Build_method_tables
: public Traverse
4236 Build_method_tables(Gogo
* gogo
,
4237 const std::vector
<Interface_type
*>& interfaces
)
4238 : Traverse(traverse_types
),
4239 gogo_(gogo
), interfaces_(interfaces
)
4248 // A list of locally defined interfaces which have hidden methods.
4249 const std::vector
<Interface_type
*>& interfaces_
;
4252 // Build all required interface method tables for types. We need to
4253 // ensure that we have an interface method table for every interface
4254 // which has a hidden method, for every named type which implements
4255 // that interface. Normally we can just build interface method tables
4256 // as we need them. However, in some cases we can require an
4257 // interface method table for an interface defined in a different
4258 // package for a type defined in that package. If that interface and
4259 // type both use a hidden method, that is OK. However, we will not be
4260 // able to build that interface method table when we need it, because
4261 // the type's hidden method will be static. So we have to build it
4262 // here, and just refer it from other packages as needed.
4265 Gogo::build_interface_method_tables()
4270 std::vector
<Interface_type
*> hidden_interfaces
;
4271 hidden_interfaces
.reserve(this->interface_types_
.size());
4272 for (std::vector
<Interface_type
*>::const_iterator pi
=
4273 this->interface_types_
.begin();
4274 pi
!= this->interface_types_
.end();
4277 const Typed_identifier_list
* methods
= (*pi
)->methods();
4278 if (methods
== NULL
)
4280 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4281 pm
!= methods
->end();
4284 if (Gogo::is_hidden_name(pm
->name()))
4286 hidden_interfaces
.push_back(*pi
);
4292 if (!hidden_interfaces
.empty())
4294 // Now traverse the tree looking for all named types.
4295 Build_method_tables
bmt(this, hidden_interfaces
);
4296 this->traverse(&bmt
);
4299 // We no longer need the list of interfaces.
4301 this->interface_types_
.clear();
4304 // This is called for each type. For a named type, for each of the
4305 // interfaces with hidden methods that it implements, create the
4309 Build_method_tables::type(Type
* type
)
4311 Named_type
* nt
= type
->named_type();
4312 Struct_type
* st
= type
->struct_type();
4313 if (nt
!= NULL
|| st
!= NULL
)
4315 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4316 for (std::vector
<Interface_type
*>::const_iterator p
=
4317 this->interfaces_
.begin();
4318 p
!= this->interfaces_
.end();
4321 // We ask whether a pointer to the named type implements the
4322 // interface, because a pointer can implement more methods
4326 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4329 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4330 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4335 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4338 st
->interface_method_table(*p
, false)->get_backend(&context
);
4339 st
->interface_method_table(*p
, true)->get_backend(&context
);
4344 return TRAVERSE_CONTINUE
;
4347 // Return an expression which allocates memory to hold values of type TYPE.
4350 Gogo::allocate_memory(Type
* type
, Location location
)
4352 Expression
* td
= Expression::make_type_descriptor(type
, location
);
4354 Expression::make_type_info(type
, Expression::TYPE_INFO_SIZE
);
4355 return Runtime::make_call(Runtime::NEW
, location
, 2, td
, size
);
4358 // Traversal class used to check for return statements.
4360 class Check_return_statements_traverse
: public Traverse
4363 Check_return_statements_traverse()
4364 : Traverse(traverse_functions
)
4368 function(Named_object
*);
4371 // Check that a function has a return statement if it needs one.
4374 Check_return_statements_traverse::function(Named_object
* no
)
4376 Function
* func
= no
->func_value();
4377 const Function_type
* fntype
= func
->type();
4378 const Typed_identifier_list
* results
= fntype
->results();
4380 // We only need a return statement if there is a return value.
4381 if (results
== NULL
|| results
->empty())
4382 return TRAVERSE_CONTINUE
;
4384 if (func
->block()->may_fall_through())
4385 error_at(func
->block()->end_location(),
4386 "missing return at end of function");
4388 return TRAVERSE_CONTINUE
;
4391 // Check return statements.
4394 Gogo::check_return_statements()
4396 Check_return_statements_traverse traverse
;
4397 this->traverse(&traverse
);
4400 // Export identifiers as requested.
4405 // For now we always stream to a section. Later we may want to
4406 // support streaming to a separate file.
4407 Stream_to_section stream
;
4409 // Write out either the prefix or pkgpath depending on how we were
4412 std::string pkgpath
;
4413 if (this->pkgpath_from_option_
)
4414 pkgpath
= this->pkgpath_
;
4415 else if (this->prefix_from_option_
)
4416 prefix
= this->prefix_
;
4417 else if (this->is_main_package())
4422 Export
exp(&stream
);
4423 exp
.register_builtin_types(this);
4424 exp
.export_globals(this->package_name(),
4429 (this->need_init_fn_
&& !this->is_main_package()
4430 ? this->get_init_fn_name()
4432 this->imported_init_fns_
,
4433 this->package_
->bindings());
4435 if (!this->c_header_
.empty() && !saw_errors())
4436 this->write_c_header();
4439 // Write the top level named struct types in C format to a C header
4440 // file. This is used when building the runtime package, to share
4441 // struct definitions between C and Go.
4444 Gogo::write_c_header()
4447 out
.open(this->c_header_
.c_str());
4450 error("cannot open %s: %m", this->c_header_
.c_str());
4454 std::list
<Named_object
*> types
;
4455 Bindings
* top
= this->package_
->bindings();
4456 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
4457 p
!= top
->end_definitions();
4460 Named_object
* no
= *p
;
4461 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
4462 types
.push_back(no
);
4463 if (no
->is_const() && no
->const_value()->type()->integer_type() != NULL
)
4465 Numeric_constant nc
;
4467 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
4468 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
4470 out
<< "#define " << no
->message_name() << ' ' << val
4476 std::vector
<const Named_object
*> written
;
4478 while (!types
.empty())
4480 Named_object
* no
= types
.front();
4483 std::vector
<const Named_object
*> requires
;
4484 std::vector
<const Named_object
*> declare
;
4485 if (!no
->type_value()->struct_type()->can_write_to_c_header(&requires
,
4490 for (std::vector
<const Named_object
*>::const_iterator pr
4492 pr
!= requires
.end() && ok
;
4495 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
4496 pt
!= types
.end() && ok
;
4506 // This should be impossible since the code parsed and
4511 types
.push_back(no
);
4515 for (std::vector
<const Named_object
*>::const_iterator pd
4517 pd
!= declare
.end();
4523 std::vector
<const Named_object
*> drequires
;
4524 std::vector
<const Named_object
*> ddeclare
;
4525 if (!(*pd
)->type_value()->struct_type()->
4526 can_write_to_c_header(&drequires
, &ddeclare
))
4530 for (std::vector
<const Named_object
*>::const_iterator pw
4532 pw
!= written
.end();
4544 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
4545 written
.push_back(*pd
);
4550 out
<< "struct " << no
->message_name() << " {" << std::endl
;
4551 no
->type_value()->struct_type()->write_to_c_header(out
);
4552 out
<< "};" << std::endl
;
4553 written
.push_back(no
);
4558 error("error writing to %s: %m", this->c_header_
.c_str());
4561 // Find the blocks in order to convert named types defined in blocks.
4563 class Convert_named_types
: public Traverse
4566 Convert_named_types(Gogo
* gogo
)
4567 : Traverse(traverse_blocks
),
4573 block(Block
* block
);
4580 Convert_named_types::block(Block
* block
)
4582 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
4583 return TRAVERSE_CONTINUE
;
4586 // Convert all named types to the backend representation. Since named
4587 // types can refer to other types, this needs to be done in the right
4588 // sequence, which is handled by Named_type::convert. Here we arrange
4589 // to call that for each named type.
4592 Gogo::convert_named_types()
4594 this->convert_named_types_in_bindings(this->globals_
);
4595 for (Packages::iterator p
= this->packages_
.begin();
4596 p
!= this->packages_
.end();
4599 Package
* package
= p
->second
;
4600 this->convert_named_types_in_bindings(package
->bindings());
4603 Convert_named_types
cnt(this);
4604 this->traverse(&cnt
);
4606 // Make all the builtin named types used for type descriptors, and
4607 // then convert them. They will only be written out if they are
4609 Type::make_type_descriptor_type();
4610 Type::make_type_descriptor_ptr_type();
4611 Function_type::make_function_type_descriptor_type();
4612 Pointer_type::make_pointer_type_descriptor_type();
4613 Struct_type::make_struct_type_descriptor_type();
4614 Array_type::make_array_type_descriptor_type();
4615 Array_type::make_slice_type_descriptor_type();
4616 Map_type::make_map_type_descriptor_type();
4617 Channel_type::make_chan_type_descriptor_type();
4618 Interface_type::make_interface_type_descriptor_type();
4619 Expression::make_func_descriptor_type();
4620 Type::convert_builtin_named_types(this);
4622 Runtime::convert_types(this);
4624 this->named_types_are_converted_
= true;
4627 // Convert all names types in a set of bindings.
4630 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
4632 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
4633 p
!= bindings
->end_definitions();
4636 if ((*p
)->is_type())
4637 (*p
)->type_value()->convert(this);
4643 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
4645 : type_(type
), enclosing_(enclosing
), results_(NULL
),
4646 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
4647 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
4648 pragmas_(0), is_sink_(false), results_are_named_(false),
4649 is_unnamed_type_stub_method_(false), calls_recover_(false),
4650 is_recover_thunk_(false), has_recover_thunk_(false),
4651 calls_defer_retaddr_(false), is_type_specific_function_(false),
4652 in_unique_section_(false)
4656 // Create the named result variables.
4659 Function::create_result_variables(Gogo
* gogo
)
4661 const Typed_identifier_list
* results
= this->type_
->results();
4662 if (results
== NULL
|| results
->empty())
4665 if (!results
->front().name().empty())
4666 this->results_are_named_
= true;
4668 this->results_
= new Results();
4669 this->results_
->reserve(results
->size());
4671 Block
* block
= this->block_
;
4673 for (Typed_identifier_list::const_iterator p
= results
->begin();
4674 p
!= results
->end();
4677 std::string name
= p
->name();
4678 if (name
.empty() || Gogo::is_sink_name(name
))
4680 static int result_counter
;
4682 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
4684 name
= gogo
->pack_hidden_name(buf
, false);
4686 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
4688 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
4689 if (no
->is_result_variable())
4690 this->results_
->push_back(no
);
4693 static int dummy_result_count
;
4695 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
4696 ++dummy_result_count
;
4697 name
= gogo
->pack_hidden_name(buf
, false);
4698 no
= block
->bindings()->add_result_variable(name
, result
);
4699 go_assert(no
->is_result_variable());
4700 this->results_
->push_back(no
);
4705 // Update the named result variables when cloning a function which
4709 Function::update_result_variables()
4711 if (this->results_
== NULL
)
4714 for (Results::iterator p
= this->results_
->begin();
4715 p
!= this->results_
->end();
4717 (*p
)->result_var_value()->set_function(this);
4720 // Whether this method should not be included in the type descriptor.
4723 Function::nointerface() const
4725 go_assert(this->is_method());
4726 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
4729 // Record that this method should not be included in the type
4733 Function::set_nointerface()
4735 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
4738 // Return the closure variable, creating it if necessary.
4741 Function::closure_var()
4743 if (this->closure_var_
== NULL
)
4745 go_assert(this->descriptor_
== NULL
);
4746 // We don't know the type of the variable yet. We add fields as
4748 Location loc
= this->type_
->location();
4749 Struct_field_list
* sfl
= new Struct_field_list
;
4750 Type
* struct_type
= Type::make_struct_type(sfl
, loc
);
4751 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
4752 NULL
, false, false, false, loc
);
4754 var
->set_is_closure();
4755 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
4756 // Note that the new variable is not in any binding contour.
4758 return this->closure_var_
;
4761 // Set the type of the closure variable.
4764 Function::set_closure_type()
4766 if (this->closure_var_
== NULL
)
4768 Named_object
* closure
= this->closure_var_
;
4769 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
4771 // The first field of a closure is always a pointer to the function
4773 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4774 st
->push_field(Struct_field(Typed_identifier(".$f", voidptr_type
,
4777 unsigned int index
= 1;
4778 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
4779 p
!= this->closure_fields_
.end();
4782 Named_object
* no
= p
->first
;
4784 snprintf(buf
, sizeof buf
, "%u", index
);
4785 std::string n
= no
->name() + buf
;
4787 if (no
->is_variable())
4788 var_type
= no
->var_value()->type();
4790 var_type
= no
->result_var_value()->type();
4791 Type
* field_type
= Type::make_pointer_type(var_type
);
4792 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
4796 // Return whether this function is a method.
4799 Function::is_method() const
4801 return this->type_
->is_method();
4804 // Add a label definition.
4807 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
4810 Label
* lnull
= NULL
;
4811 std::pair
<Labels::iterator
, bool> ins
=
4812 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4814 if (label_name
== "_")
4816 label
= Label::create_dummy_label();
4818 ins
.first
->second
= label
;
4820 else if (ins
.second
)
4822 // This is a new label.
4823 label
= new Label(label_name
);
4824 ins
.first
->second
= label
;
4828 // The label was already in the hash table.
4829 label
= ins
.first
->second
;
4830 if (label
->is_defined())
4832 error_at(location
, "label %qs already defined",
4833 Gogo::message_name(label_name
).c_str());
4834 inform(label
->location(), "previous definition of %qs was here",
4835 Gogo::message_name(label_name
).c_str());
4836 return new Label(label_name
);
4840 label
->define(location
, gogo
->bindings_snapshot(location
));
4842 // Issue any errors appropriate for any previous goto's to this
4844 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
4845 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
4848 (*p
)->check_goto_to(gogo
->current_block());
4849 label
->clear_refs();
4854 // Add a reference to a label.
4857 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
4858 Location location
, bool issue_goto_errors
)
4860 Label
* lnull
= NULL
;
4861 std::pair
<Labels::iterator
, bool> ins
=
4862 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4866 // The label was already in the hash table.
4867 label
= ins
.first
->second
;
4871 go_assert(ins
.first
->second
== NULL
);
4872 label
= new Label(label_name
);
4873 ins
.first
->second
= label
;
4876 label
->set_is_used();
4878 if (issue_goto_errors
)
4880 Bindings_snapshot
* snapshot
= label
->snapshot();
4881 if (snapshot
!= NULL
)
4882 snapshot
->check_goto_from(gogo
->current_block(), location
);
4884 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
4890 // Warn about labels that are defined but not used.
4893 Function::check_labels() const
4895 for (Labels::const_iterator p
= this->labels_
.begin();
4896 p
!= this->labels_
.end();
4899 Label
* label
= p
->second
;
4900 if (!label
->is_used())
4901 error_at(label
->location(), "label %qs defined and not used",
4902 Gogo::message_name(label
->name()).c_str());
4906 // Swap one function with another. This is used when building the
4907 // thunk we use to call a function which calls recover. It may not
4908 // work for any other case.
4911 Function::swap_for_recover(Function
*x
)
4913 go_assert(this->enclosing_
== x
->enclosing_
);
4914 std::swap(this->results_
, x
->results_
);
4915 std::swap(this->closure_var_
, x
->closure_var_
);
4916 std::swap(this->block_
, x
->block_
);
4917 go_assert(this->location_
== x
->location_
);
4918 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
4919 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
4922 // Traverse the tree.
4925 Function::traverse(Traverse
* traverse
)
4927 unsigned int traverse_mask
= traverse
->traverse_mask();
4930 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
4933 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
4934 return TRAVERSE_EXIT
;
4937 // FIXME: We should check traverse_functions here if nested
4938 // functions are stored in block bindings.
4939 if (this->block_
!= NULL
4941 & (Traverse::traverse_variables
4942 | Traverse::traverse_constants
4943 | Traverse::traverse_blocks
4944 | Traverse::traverse_statements
4945 | Traverse::traverse_expressions
4946 | Traverse::traverse_types
)) != 0)
4948 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
4949 return TRAVERSE_EXIT
;
4952 return TRAVERSE_CONTINUE
;
4955 // Work out types for unspecified variables and constants.
4958 Function::determine_types()
4960 if (this->block_
!= NULL
)
4961 this->block_
->determine_types();
4964 // Return the function descriptor, the value you get when you refer to
4965 // the function in Go code without calling it.
4968 Function::descriptor(Gogo
*, Named_object
* no
)
4970 go_assert(!this->is_method());
4971 go_assert(this->closure_var_
== NULL
);
4972 if (this->descriptor_
== NULL
)
4973 this->descriptor_
= Expression::make_func_descriptor(no
);
4974 return this->descriptor_
;
4977 // Get a pointer to the variable representing the defer stack for this
4978 // function, making it if necessary. The value of the variable is set
4979 // by the runtime routines to true if the function is returning,
4980 // rather than panicing through. A pointer to this variable is used
4981 // as a marker for the functions on the defer stack associated with
4982 // this function. A function-specific variable permits inlining a
4983 // function which uses defer.
4986 Function::defer_stack(Location location
)
4988 if (this->defer_stack_
== NULL
)
4990 Type
* t
= Type::lookup_bool_type();
4991 Expression
* n
= Expression::make_boolean(false, location
);
4992 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
4993 this->defer_stack_
->set_is_address_taken();
4995 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
4997 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5000 // Export the function.
5003 Function::export_func(Export
* exp
, const std::string
& name
) const
5005 Function::export_func_with_type(exp
, name
, this->type_
);
5008 // Export a function with a type.
5011 Function::export_func_with_type(Export
* exp
, const std::string
& name
,
5012 const Function_type
* fntype
)
5014 exp
->write_c_string("func ");
5016 if (fntype
->is_method())
5018 exp
->write_c_string("(");
5019 const Typed_identifier
* receiver
= fntype
->receiver();
5020 exp
->write_name(receiver
->name());
5021 exp
->write_escape(receiver
->note());
5022 exp
->write_c_string(" ");
5023 exp
->write_type(receiver
->type());
5024 exp
->write_c_string(") ");
5027 exp
->write_string(name
);
5029 exp
->write_c_string(" (");
5030 const Typed_identifier_list
* parameters
= fntype
->parameters();
5031 if (parameters
!= NULL
)
5034 bool is_varargs
= fntype
->is_varargs();
5036 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5037 p
!= parameters
->end();
5043 exp
->write_c_string(", ");
5044 exp
->write_name(p
->name());
5045 exp
->write_escape(p
->note());
5046 exp
->write_c_string(" ");
5047 if (!is_varargs
|| p
+ 1 != parameters
->end())
5048 exp
->write_type(p
->type());
5051 exp
->write_c_string("...");
5052 exp
->write_type(p
->type()->array_type()->element_type());
5056 exp
->write_c_string(")");
5058 const Typed_identifier_list
* results
= fntype
->results();
5059 if (results
!= NULL
)
5061 if (results
->size() == 1 && results
->begin()->name().empty())
5063 exp
->write_c_string(" ");
5064 exp
->write_type(results
->begin()->type());
5068 exp
->write_c_string(" (");
5070 for (Typed_identifier_list::const_iterator p
= results
->begin();
5071 p
!= results
->end();
5077 exp
->write_c_string(", ");
5078 exp
->write_name(p
->name());
5079 exp
->write_escape(p
->note());
5080 exp
->write_c_string(" ");
5081 exp
->write_type(p
->type());
5083 exp
->write_c_string(")");
5086 exp
->write_c_string(";\n");
5089 // Import a function.
5092 Function::import_func(Import
* imp
, std::string
* pname
,
5093 Typed_identifier
** preceiver
,
5094 Typed_identifier_list
** pparameters
,
5095 Typed_identifier_list
** presults
,
5098 imp
->require_c_string("func ");
5101 if (imp
->peek_char() == '(')
5103 imp
->require_c_string("(");
5104 std::string name
= imp
->read_name();
5105 std::string escape_note
= imp
->read_escape();
5106 imp
->require_c_string(" ");
5107 Type
* rtype
= imp
->read_type();
5108 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
5109 (*preceiver
)->set_note(escape_note
);
5110 imp
->require_c_string(") ");
5113 *pname
= imp
->read_identifier();
5115 Typed_identifier_list
* parameters
;
5116 *is_varargs
= false;
5117 imp
->require_c_string(" (");
5118 if (imp
->peek_char() == ')')
5122 parameters
= new Typed_identifier_list();
5125 std::string name
= imp
->read_name();
5126 std::string escape_note
= imp
->read_escape();
5127 imp
->require_c_string(" ");
5129 if (imp
->match_c_string("..."))
5135 Type
* ptype
= imp
->read_type();
5137 ptype
= Type::make_array_type(ptype
, NULL
);
5138 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
5139 t
.set_note(escape_note
);
5140 parameters
->push_back(t
);
5141 if (imp
->peek_char() != ',')
5143 go_assert(!*is_varargs
);
5144 imp
->require_c_string(", ");
5147 imp
->require_c_string(")");
5148 *pparameters
= parameters
;
5150 Typed_identifier_list
* results
;
5151 if (imp
->peek_char() != ' ')
5155 results
= new Typed_identifier_list();
5156 imp
->require_c_string(" ");
5157 if (imp
->peek_char() != '(')
5159 Type
* rtype
= imp
->read_type();
5160 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
5164 imp
->require_c_string("(");
5167 std::string name
= imp
->read_name();
5168 std::string note
= imp
->read_escape();
5169 imp
->require_c_string(" ");
5170 Type
* rtype
= imp
->read_type();
5171 Typed_identifier t
= Typed_identifier(name
, rtype
,
5174 results
->push_back(t
);
5175 if (imp
->peek_char() != ',')
5177 imp
->require_c_string(", ");
5179 imp
->require_c_string(")");
5182 imp
->require_c_string(";\n");
5183 *presults
= results
;
5186 // Get the backend representation.
5189 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5191 if (this->fndecl_
== NULL
)
5193 std::string asm_name
;
5194 bool is_visible
= false;
5195 if (no
->package() != NULL
)
5197 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
5199 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
5200 && !this->type_
->is_method())
5202 else if (no
->name() == gogo
->get_init_fn_name())
5205 asm_name
= no
->name();
5207 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
5208 && gogo
->is_main_package())
5210 // Methods have to be public even if they are hidden because
5211 // they can be pulled into type descriptors when using
5212 // anonymous fields.
5213 else if (!Gogo::is_hidden_name(no
->name())
5214 || this->type_
->is_method())
5216 if (!this->is_unnamed_type_stub_method_
)
5218 std::string pkgpath
= gogo
->pkgpath_symbol();
5219 if (this->type_
->is_method()
5220 && Gogo::is_hidden_name(no
->name())
5221 && Gogo::hidden_name_pkgpath(no
->name()) != gogo
->pkgpath())
5223 // This is a method we created for an unexported
5224 // method of an imported embedded type. We need to
5225 // use the pkgpath of the imported package to avoid
5226 // a possible name collision. See bug478 for a test
5228 pkgpath
= Gogo::hidden_name_pkgpath(no
->name());
5229 pkgpath
= Gogo::pkgpath_for_symbol(pkgpath
);
5233 asm_name
.append(1, '.');
5234 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5235 if (this->type_
->is_method())
5237 asm_name
.append(1, '.');
5238 Type
* rtype
= this->type_
->receiver()->type();
5239 asm_name
.append(rtype
->mangled_name(gogo
));
5243 if (!this->asm_name_
.empty())
5245 asm_name
= this->asm_name_
;
5249 // If a function calls the predeclared recover function, we
5250 // can't inline it, because recover behaves differently in a
5251 // function passed directly to defer. If this is a recover
5252 // thunk that we built to test whether a function can be
5253 // recovered, we can't inline it, because that will mess up
5254 // our return address comparison.
5255 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
5257 // If a function calls __go_set_defer_retaddr, then mark it as
5258 // uninlinable. This prevents the GCC backend from splitting
5259 // the function; splitting the function is a bad idea because we
5260 // want the return address label to be in the same function as
5262 if (this->calls_defer_retaddr_
)
5263 is_inlinable
= false;
5265 // Check the //go:noinline compiler directive.
5266 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
5267 is_inlinable
= false;
5269 // If this is a thunk created to call a function which calls
5270 // the predeclared recover function, we need to disable
5271 // stack splitting for the thunk.
5272 bool disable_split_stack
= this->is_recover_thunk_
;
5274 // Check the //go:nosplit compiler directive.
5275 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
5276 disable_split_stack
= true;
5278 // This should go into a unique section if that has been
5279 // requested elsewhere, or if this is a nointerface function.
5280 // We want to put a nointerface function into a unique section
5281 // because there is a good chance that the linker garbage
5282 // collection can discard it.
5283 bool in_unique_section
= (this->in_unique_section_
5284 || (this->is_method() && this->nointerface()));
5286 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
5288 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5289 is_visible
, false, is_inlinable
,
5290 disable_split_stack
, in_unique_section
,
5293 return this->fndecl_
;
5296 // Get the backend representation.
5299 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5301 if (this->fndecl_
== NULL
)
5303 // Let Go code use an asm declaration to pick up a builtin
5305 if (!this->asm_name_
.empty())
5307 Bfunction
* builtin_decl
=
5308 gogo
->backend()->lookup_builtin(this->asm_name_
);
5309 if (builtin_decl
!= NULL
)
5311 this->fndecl_
= builtin_decl
;
5312 return this->fndecl_
;
5316 std::string asm_name
;
5317 if (this->asm_name_
.empty())
5319 asm_name
= (no
->package() == NULL
5320 ? gogo
->pkgpath_symbol()
5321 : no
->package()->pkgpath_symbol());
5322 asm_name
.append(1, '.');
5323 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5324 if (this->fntype_
->is_method())
5326 asm_name
.append(1, '.');
5327 Type
* rtype
= this->fntype_
->receiver()->type();
5328 asm_name
.append(rtype
->mangled_name(gogo
));
5332 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
5334 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5335 true, true, true, false, false,
5339 return this->fndecl_
;
5342 // Build the descriptor for a function declaration. This won't
5343 // necessarily happen if the package has just a declaration for the
5344 // function and no other reference to it, but we may still need the
5345 // descriptor for references from other packages.
5347 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
5349 if (this->descriptor_
!= NULL
)
5351 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5352 this->descriptor_
->get_backend(&context
);
5356 // Check that the types used in this declaration's signature are defined.
5357 // Reports errors for any undefined type.
5360 Function_declaration::check_types() const
5362 // Calling Type::base will give errors for any undefined types.
5363 Function_type
* fntype
= this->type();
5364 if (fntype
->receiver() != NULL
)
5365 fntype
->receiver()->type()->base();
5366 if (fntype
->parameters() != NULL
)
5368 const Typed_identifier_list
* params
= fntype
->parameters();
5369 for (Typed_identifier_list::const_iterator p
= params
->begin();
5376 // Return the function's decl after it has been built.
5379 Function::get_decl() const
5381 go_assert(this->fndecl_
!= NULL
);
5382 return this->fndecl_
;
5385 // Build the backend representation for the function code.
5388 Function::build(Gogo
* gogo
, Named_object
* named_function
)
5390 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5392 // A list of parameter variables for this function.
5393 std::vector
<Bvariable
*> param_vars
;
5395 // Variables that need to be declared for this function and their
5397 std::vector
<Bvariable
*> vars
;
5398 std::vector
<Bexpression
*> var_inits
;
5399 for (Bindings::const_definitions_iterator p
=
5400 this->block_
->bindings()->begin_definitions();
5401 p
!= this->block_
->bindings()->end_definitions();
5404 Location loc
= (*p
)->location();
5405 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
5407 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5408 Bvariable
* parm_bvar
= bvar
;
5410 // We always pass the receiver to a method as a pointer. If
5411 // the receiver is declared as a non-pointer type, then we
5412 // copy the value into a local variable.
5413 if ((*p
)->var_value()->is_receiver()
5414 && (*p
)->var_value()->type()->points_to() == NULL
)
5416 std::string name
= (*p
)->name() + ".pointer";
5417 Type
* var_type
= (*p
)->var_value()->type();
5418 Variable
* parm_var
=
5419 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
5421 Named_object
* parm_no
=
5422 Named_object::make_variable(name
, NULL
, parm_var
);
5423 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5425 vars
.push_back(bvar
);
5426 Expression
* parm_ref
=
5427 Expression::make_var_reference(parm_no
, loc
);
5428 parm_ref
= Expression::make_unary(OPERATOR_MULT
, parm_ref
, loc
);
5429 if ((*p
)->var_value()->is_in_heap())
5430 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
5431 var_inits
.push_back(parm_ref
->get_backend(&context
));
5433 else if ((*p
)->var_value()->is_in_heap())
5435 // If we take the address of a parameter, then we need
5436 // to copy it into the heap.
5437 std::string parm_name
= (*p
)->name() + ".param";
5438 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
5439 false, true, false, loc
);
5440 Named_object
* parm_no
=
5441 Named_object::make_variable(parm_name
, NULL
, parm_var
);
5442 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5444 vars
.push_back(bvar
);
5445 Expression
* var_ref
=
5446 Expression::make_var_reference(parm_no
, loc
);
5447 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
5448 var_inits
.push_back(var_ref
->get_backend(&context
));
5450 param_vars
.push_back(parm_bvar
);
5452 else if ((*p
)->is_result_variable())
5454 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5456 Type
* type
= (*p
)->result_var_value()->type();
5458 if (!(*p
)->result_var_value()->is_in_heap())
5460 Btype
* btype
= type
->get_backend(gogo
);
5461 init
= gogo
->backend()->zero_expression(btype
);
5464 init
= Expression::make_allocation(type
,
5465 loc
)->get_backend(&context
);
5467 vars
.push_back(bvar
);
5468 var_inits
.push_back(init
);
5471 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
5473 go_assert(saw_errors());
5477 // If we need a closure variable, make sure to create it.
5478 // It gets installed in the function as a side effect of creation.
5479 if (this->closure_var_
!= NULL
)
5481 go_assert(this->closure_var_
->var_value()->is_closure());
5482 this->closure_var_
->get_backend_variable(gogo
, named_function
);
5485 if (this->block_
!= NULL
)
5487 // Declare variables if necessary.
5488 Bblock
* var_decls
= NULL
;
5490 Bstatement
* defer_init
= NULL
;
5491 if (!vars
.empty() || this->defer_stack_
!= NULL
)
5494 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
5495 this->block_
->start_location(),
5496 this->block_
->end_location());
5498 if (this->defer_stack_
!= NULL
)
5500 Translate_context
dcontext(gogo
, named_function
, this->block_
,
5502 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
5506 // Build the backend representation for all the statements in the
5508 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5509 Bblock
* code_block
= this->block_
->get_backend(&context
);
5511 // Initialize variables if necessary.
5512 std::vector
<Bstatement
*> init
;
5513 go_assert(vars
.size() == var_inits
.size());
5514 for (size_t i
= 0; i
< vars
.size(); ++i
)
5516 Bstatement
* init_stmt
=
5517 gogo
->backend()->init_statement(vars
[i
], var_inits
[i
]);
5518 init
.push_back(init_stmt
);
5520 if (defer_init
!= NULL
)
5521 init
.push_back(defer_init
);
5522 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
5524 // Initialize all variables before executing this code block.
5525 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
5526 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
5528 // If we have a defer stack, initialize it at the start of a
5530 Bstatement
* except
= NULL
;
5531 Bstatement
* fini
= NULL
;
5532 if (defer_init
!= NULL
)
5534 // Clean up the defer stack when we leave the function.
5535 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
5537 // Wrap the code for this function in an exception handler to handle
5540 gogo
->backend()->exception_handler_statement(code_stmt
,
5545 // Stick the code into the block we built for the receiver, if
5547 if (var_decls
!= NULL
)
5549 std::vector
<Bstatement
*> code_stmt_list(1, code_stmt
);
5550 gogo
->backend()->block_add_statements(var_decls
, code_stmt_list
);
5551 code_stmt
= gogo
->backend()->block_statement(var_decls
);
5554 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
5556 go_assert(saw_errors());
5561 // If we created a descriptor for the function, make sure we emit it.
5562 if (this->descriptor_
!= NULL
)
5564 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5565 this->descriptor_
->get_backend(&context
);
5569 // Build the wrappers around function code needed if the function has
5570 // any defer statements. This sets *EXCEPT to an exception handler
5571 // and *FINI to a finally handler.
5574 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
5575 Bstatement
** except
, Bstatement
** fini
)
5577 Location end_loc
= this->block_
->end_location();
5579 // Add an exception handler. This is used if a panic occurs. Its
5580 // purpose is to stop the stack unwinding if a deferred function
5581 // calls recover. There are more details in
5582 // libgo/runtime/go-unwind.c.
5584 std::vector
<Bstatement
*> stmts
;
5585 Expression
* call
= Runtime::make_call(Runtime::CHECK_DEFER
, end_loc
, 1,
5586 this->defer_stack(end_loc
));
5587 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5588 Bexpression
* defer
= call
->get_backend(&context
);
5589 stmts
.push_back(gogo
->backend()->expression_statement(defer
));
5591 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5592 if (ret_bstmt
!= NULL
)
5593 stmts
.push_back(ret_bstmt
);
5595 go_assert(*except
== NULL
);
5596 *except
= gogo
->backend()->statement_list(stmts
);
5598 call
= Runtime::make_call(Runtime::CHECK_DEFER
, end_loc
, 1,
5599 this->defer_stack(end_loc
));
5600 defer
= call
->get_backend(&context
);
5602 call
= Runtime::make_call(Runtime::UNDEFER
, end_loc
, 1,
5603 this->defer_stack(end_loc
));
5604 Bexpression
* undefer
= call
->get_backend(&context
);
5605 Bstatement
* function_defer
=
5606 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
5608 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
5609 if (this->type_
->results() != NULL
5610 && !this->type_
->results()->empty()
5611 && !this->type_
->results()->front().name().empty())
5613 // If the result variables are named, and we are returning from
5614 // this function rather than panicing through it, we need to
5615 // return them again, because they might have been changed by a
5616 // defer function. The runtime routines set the defer_stack
5617 // variable to true if we are returning from this function.
5619 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5620 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
5622 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
5624 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
5625 Bexpression
* bref
= ref
->get_backend(&context
);
5626 ret
= gogo
->backend()->conditional_expression(NULL
, bref
, ret
, NULL
,
5628 stmts
.push_back(gogo
->backend()->expression_statement(ret
));
5631 go_assert(*fini
== NULL
);
5632 *fini
= gogo
->backend()->statement_list(stmts
);
5635 // Return the statement that assigns values to this function's result struct.
5638 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
5639 Location location
) const
5641 const Typed_identifier_list
* results
= this->type_
->results();
5642 if (results
== NULL
|| results
->empty())
5645 go_assert(this->results_
!= NULL
);
5646 if (this->results_
->size() != results
->size())
5648 go_assert(saw_errors());
5649 return gogo
->backend()->error_statement();
5652 std::vector
<Bexpression
*> vals(results
->size());
5653 for (size_t i
= 0; i
< vals
.size(); ++i
)
5655 Named_object
* no
= (*this->results_
)[i
];
5656 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
5657 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
5658 if (no
->result_var_value()->is_in_heap())
5660 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
5661 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
5665 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
5670 Block::Block(Block
* enclosing
, Location location
)
5671 : enclosing_(enclosing
), statements_(),
5672 bindings_(new Bindings(enclosing
== NULL
5674 : enclosing
->bindings())),
5675 start_location_(location
),
5676 end_location_(UNKNOWN_LOCATION
)
5680 // Add a statement to a block.
5683 Block::add_statement(Statement
* statement
)
5685 this->statements_
.push_back(statement
);
5688 // Add a statement to the front of a block. This is slow but is only
5689 // used for reference counts of parameters.
5692 Block::add_statement_at_front(Statement
* statement
)
5694 this->statements_
.insert(this->statements_
.begin(), statement
);
5697 // Replace a statement in a block.
5700 Block::replace_statement(size_t index
, Statement
* s
)
5702 go_assert(index
< this->statements_
.size());
5703 this->statements_
[index
] = s
;
5706 // Add a statement before another statement.
5709 Block::insert_statement_before(size_t index
, Statement
* s
)
5711 go_assert(index
< this->statements_
.size());
5712 this->statements_
.insert(this->statements_
.begin() + index
, s
);
5715 // Add a statement after another statement.
5718 Block::insert_statement_after(size_t index
, Statement
* s
)
5720 go_assert(index
< this->statements_
.size());
5721 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
5724 // Traverse the tree.
5727 Block::traverse(Traverse
* traverse
)
5729 unsigned int traverse_mask
= traverse
->traverse_mask();
5731 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
5733 int t
= traverse
->block(this);
5734 if (t
== TRAVERSE_EXIT
)
5735 return TRAVERSE_EXIT
;
5736 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
5737 return TRAVERSE_CONTINUE
;
5741 & (Traverse::traverse_variables
5742 | Traverse::traverse_constants
5743 | Traverse::traverse_expressions
5744 | Traverse::traverse_types
)) != 0)
5746 const unsigned int e_or_t
= (Traverse::traverse_expressions
5747 | Traverse::traverse_types
);
5748 const unsigned int e_or_t_or_s
= (e_or_t
5749 | Traverse::traverse_statements
);
5750 for (Bindings::const_definitions_iterator pb
=
5751 this->bindings_
->begin_definitions();
5752 pb
!= this->bindings_
->end_definitions();
5755 int t
= TRAVERSE_CONTINUE
;
5756 switch ((*pb
)->classification())
5758 case Named_object::NAMED_OBJECT_CONST
:
5759 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
5760 t
= traverse
->constant(*pb
, false);
5761 if (t
== TRAVERSE_CONTINUE
5762 && (traverse_mask
& e_or_t
) != 0)
5764 Type
* tc
= (*pb
)->const_value()->type();
5766 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
5767 return TRAVERSE_EXIT
;
5768 t
= (*pb
)->const_value()->traverse_expression(traverse
);
5772 case Named_object::NAMED_OBJECT_VAR
:
5773 case Named_object::NAMED_OBJECT_RESULT_VAR
:
5774 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
5775 t
= traverse
->variable(*pb
);
5776 if (t
== TRAVERSE_CONTINUE
5777 && (traverse_mask
& e_or_t
) != 0)
5779 if ((*pb
)->is_result_variable()
5780 || (*pb
)->var_value()->has_type())
5782 Type
* tv
= ((*pb
)->is_variable()
5783 ? (*pb
)->var_value()->type()
5784 : (*pb
)->result_var_value()->type());
5786 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
5787 return TRAVERSE_EXIT
;
5790 if (t
== TRAVERSE_CONTINUE
5791 && (traverse_mask
& e_or_t_or_s
) != 0
5792 && (*pb
)->is_variable())
5793 t
= (*pb
)->var_value()->traverse_expression(traverse
,
5797 case Named_object::NAMED_OBJECT_FUNC
:
5798 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
5801 case Named_object::NAMED_OBJECT_TYPE
:
5802 if ((traverse_mask
& e_or_t
) != 0)
5803 t
= Type::traverse((*pb
)->type_value(), traverse
);
5806 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
5807 case Named_object::NAMED_OBJECT_UNKNOWN
:
5808 case Named_object::NAMED_OBJECT_ERRONEOUS
:
5811 case Named_object::NAMED_OBJECT_PACKAGE
:
5812 case Named_object::NAMED_OBJECT_SINK
:
5819 if (t
== TRAVERSE_EXIT
)
5820 return TRAVERSE_EXIT
;
5824 // No point in checking traverse_mask here--if we got here we always
5825 // want to walk the statements. The traversal can insert new
5826 // statements before or after the current statement. Inserting
5827 // statements before the current statement requires updating I via
5828 // the pointer; those statements will not be traversed. Any new
5829 // statements inserted after the current statement will be traversed
5831 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
5833 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
5834 return TRAVERSE_EXIT
;
5837 return TRAVERSE_CONTINUE
;
5840 // Work out types for unspecified variables and constants.
5843 Block::determine_types()
5845 for (Bindings::const_definitions_iterator pb
=
5846 this->bindings_
->begin_definitions();
5847 pb
!= this->bindings_
->end_definitions();
5850 if ((*pb
)->is_variable())
5851 (*pb
)->var_value()->determine_type();
5852 else if ((*pb
)->is_const())
5853 (*pb
)->const_value()->determine_type();
5856 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
5857 ps
!= this->statements_
.end();
5859 (*ps
)->determine_types();
5862 // Return true if the statements in this block may fall through.
5865 Block::may_fall_through() const
5867 if (this->statements_
.empty())
5869 return this->statements_
.back()->may_fall_through();
5872 // Convert a block to the backend representation.
5875 Block::get_backend(Translate_context
* context
)
5877 Gogo
* gogo
= context
->gogo();
5878 Named_object
* function
= context
->function();
5879 std::vector
<Bvariable
*> vars
;
5880 vars
.reserve(this->bindings_
->size_definitions());
5881 for (Bindings::const_definitions_iterator pv
=
5882 this->bindings_
->begin_definitions();
5883 pv
!= this->bindings_
->end_definitions();
5886 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
5887 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
5890 go_assert(function
!= NULL
);
5891 Bfunction
* bfunction
=
5892 function
->func_value()->get_or_make_decl(gogo
, function
);
5893 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
5894 vars
, this->start_location_
,
5895 this->end_location_
);
5897 Translate_context
subcontext(gogo
, function
, this, ret
);
5898 std::vector
<Bstatement
*> bstatements
;
5899 bstatements
.reserve(this->statements_
.size());
5900 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
5901 p
!= this->statements_
.end();
5903 bstatements
.push_back((*p
)->get_backend(&subcontext
));
5905 context
->backend()->block_add_statements(ret
, bstatements
);
5910 // Class Bindings_snapshot.
5912 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
5913 : block_(b
), counts_(), location_(location
)
5917 this->counts_
.push_back(b
->bindings()->size_definitions());
5922 // Report errors appropriate for a goto from B to this.
5925 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
5928 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
5930 this->check_goto_defs(loc
, this->block_
,
5931 this->block_
->bindings()->size_definitions(),
5935 // Report errors appropriate for a goto from this to B.
5938 Bindings_snapshot::check_goto_to(const Block
* b
)
5941 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
5943 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
5944 b
->bindings()->size_definitions());
5947 // Report errors appropriate for a goto at LOC from BFROM to BTO.
5948 // Return true if all is well, false if we reported an error. If this
5949 // returns true, it sets *PINDEX to the number of blocks BTO is above
5953 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
5954 const Block
* bto
, size_t* pindex
)
5956 // It is an error if BTO is not either BFROM or above BFROM.
5958 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
5962 error_at(loc
, "goto jumps into block");
5963 inform(bto
->start_location(), "goto target block starts here");
5971 // Report errors appropriate for a goto at LOC ending at BLOCK, where
5972 // CFROM is the number of names defined at the point of the goto and
5973 // CTO is the number of names defined at the point of the label.
5976 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
5977 size_t cfrom
, size_t cto
)
5981 Bindings::const_definitions_iterator p
=
5982 block
->bindings()->begin_definitions();
5983 for (size_t i
= 0; i
< cfrom
; ++i
)
5985 go_assert(p
!= block
->bindings()->end_definitions());
5988 go_assert(p
!= block
->bindings()->end_definitions());
5990 std::string n
= (*p
)->message_name();
5991 error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
5992 inform((*p
)->location(), "%qs defined here", n
.c_str());
5996 // Class Function_declaration.
5998 // Return the function descriptor.
6001 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
6003 go_assert(!this->fntype_
->is_method());
6004 if (this->descriptor_
== NULL
)
6005 this->descriptor_
= Expression::make_func_descriptor(no
);
6006 return this->descriptor_
;
6011 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
6012 bool is_parameter
, bool is_receiver
,
6014 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
6015 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
6016 is_closure_(false), is_receiver_(is_receiver
),
6017 is_varargs_parameter_(false), is_used_(false),
6018 is_address_taken_(false), is_non_escaping_address_taken_(false),
6019 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6020 type_from_init_tuple_(false), type_from_range_index_(false),
6021 type_from_range_value_(false), type_from_chan_element_(false),
6022 is_type_switch_var_(false), determined_type_(false),
6023 in_unique_section_(false), escapes_(true)
6025 go_assert(type
!= NULL
|| init
!= NULL
);
6026 go_assert(!is_parameter
|| init
== NULL
);
6029 // Traverse the initializer expression.
6032 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
6034 if (this->preinit_
!= NULL
)
6036 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
6037 return TRAVERSE_EXIT
;
6039 if (this->init_
!= NULL
6041 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
6044 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
6045 return TRAVERSE_EXIT
;
6047 return TRAVERSE_CONTINUE
;
6050 // Lower the initialization expression after parsing is complete.
6053 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
6054 Statement_inserter
* inserter
)
6056 Named_object
* dep
= gogo
->var_depends_on(this);
6057 if (dep
!= NULL
&& dep
->is_variable())
6058 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
6060 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
6064 // We will give an error elsewhere, this is just to prevent
6065 // an infinite loop.
6070 Statement_inserter global_inserter
;
6071 if (this->is_global_
)
6073 global_inserter
= Statement_inserter(gogo
, this);
6074 inserter
= &global_inserter
;
6077 gogo
->lower_expression(function
, inserter
, &this->init_
);
6079 this->seen_
= false;
6081 this->init_is_lowered_
= true;
6085 // Flatten the initialization expression after ordering evaluations.
6088 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
6089 Statement_inserter
* inserter
)
6091 Named_object
* dep
= gogo
->var_depends_on(this);
6092 if (dep
!= NULL
&& dep
->is_variable())
6093 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
6095 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
6099 // We will give an error elsewhere, this is just to prevent
6100 // an infinite loop.
6105 Statement_inserter global_inserter
;
6106 if (this->is_global_
)
6108 global_inserter
= Statement_inserter(gogo
, this);
6109 inserter
= &global_inserter
;
6112 gogo
->flatten_expression(function
, inserter
, &this->init_
);
6114 // If an interface conversion is needed, we need a temporary
6116 if (this->type_
!= NULL
6117 && !Type::are_identical(this->type_
, this->init_
->type(), false,
6119 && this->init_
->type()->interface_type() != NULL
6120 && !this->init_
->is_variable())
6122 Temporary_statement
* temp
=
6123 Statement::make_temporary(NULL
, this->init_
, this->location_
);
6124 inserter
->insert(temp
);
6125 this->init_
= Expression::make_temporary_reference(temp
,
6129 this->seen_
= false;
6130 this->init_is_flattened_
= true;
6134 // Get the preinit block.
6137 Variable::preinit_block(Gogo
* gogo
)
6139 go_assert(this->is_global_
);
6140 if (this->preinit_
== NULL
)
6141 this->preinit_
= new Block(NULL
, this->location());
6143 // If a global variable has a preinitialization statement, then we
6144 // need to have an initialization function.
6145 gogo
->set_need_init_fn();
6147 return this->preinit_
;
6150 // Add a statement to be run before the initialization expression.
6153 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
6155 Block
* b
= this->preinit_block(gogo
);
6156 b
->add_statement(s
);
6157 b
->set_end_location(s
->location());
6160 // Whether this variable has a type.
6163 Variable::has_type() const
6165 if (this->type_
== NULL
)
6168 // A variable created in a type switch case nil does not actually
6169 // have a type yet. It will be changed to use the initializer's
6170 // type in determine_type.
6171 if (this->is_type_switch_var_
6172 && this->type_
->is_nil_constant_as_type())
6178 // In an assignment which sets a variable to a tuple of EXPR, return
6179 // the type of the first element of the tuple.
6182 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
6184 if (expr
->map_index_expression() != NULL
)
6186 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
6188 return Type::make_error_type();
6189 return mt
->val_type();
6191 else if (expr
->receive_expression() != NULL
)
6193 Expression
* channel
= expr
->receive_expression()->channel();
6194 Type
* channel_type
= channel
->type();
6195 if (channel_type
->channel_type() == NULL
)
6196 return Type::make_error_type();
6197 return channel_type
->channel_type()->element_type();
6202 error_at(this->location(), "invalid tuple definition");
6203 return Type::make_error_type();
6207 // Given EXPR used in a range clause, return either the index type or
6208 // the value type of the range, depending upon GET_INDEX_TYPE.
6211 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
6212 bool report_error
) const
6214 Type
* t
= expr
->type();
6215 if (t
->array_type() != NULL
6216 || (t
->points_to() != NULL
6217 && t
->points_to()->array_type() != NULL
6218 && !t
->points_to()->is_slice_type()))
6221 return Type::lookup_integer_type("int");
6223 return t
->deref()->array_type()->element_type();
6225 else if (t
->is_string_type())
6228 return Type::lookup_integer_type("int");
6230 return Type::lookup_integer_type("int32");
6232 else if (t
->map_type() != NULL
)
6235 return t
->map_type()->key_type();
6237 return t
->map_type()->val_type();
6239 else if (t
->channel_type() != NULL
)
6242 return t
->channel_type()->element_type();
6246 error_at(this->location(),
6247 "invalid definition of value variable for channel range");
6248 return Type::make_error_type();
6254 error_at(this->location(), "invalid type for range clause");
6255 return Type::make_error_type();
6259 // EXPR should be a channel. Return the channel's element type.
6262 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
6264 Type
* t
= expr
->type();
6265 if (t
->channel_type() != NULL
)
6266 return t
->channel_type()->element_type();
6270 error_at(this->location(), "expected channel");
6271 return Type::make_error_type();
6275 // Return the type of the Variable. This may be called before
6276 // Variable::determine_type is called, which means that we may need to
6277 // get the type from the initializer. FIXME: If we combine lowering
6278 // with type determination, then this should be unnecessary.
6283 // A variable in a type switch with a nil case will have the wrong
6284 // type here. This gets fixed up in determine_type, below.
6285 Type
* type
= this->type_
;
6286 Expression
* init
= this->init_
;
6287 if (this->is_type_switch_var_
6289 && this->type_
->is_nil_constant_as_type())
6291 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6292 go_assert(tge
!= NULL
);
6299 if (this->type_
== NULL
|| !this->type_
->is_error_type())
6301 error_at(this->location_
, "variable initializer refers to itself");
6302 this->type_
= Type::make_error_type();
6311 else if (this->type_from_init_tuple_
)
6312 type
= this->type_from_tuple(init
, false);
6313 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6314 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
6315 else if (this->type_from_chan_element_
)
6316 type
= this->type_from_chan_element(init
, false);
6319 go_assert(init
!= NULL
);
6320 type
= init
->type();
6321 go_assert(type
!= NULL
);
6323 // Variables should not have abstract types.
6324 if (type
->is_abstract())
6325 type
= type
->make_non_abstract_type();
6327 if (type
->is_void_type())
6328 type
= Type::make_error_type();
6331 this->seen_
= false;
6336 // Fetch the type from a const pointer, in which case it should have
6337 // been set already.
6340 Variable::type() const
6342 go_assert(this->type_
!= NULL
);
6346 // Set the type if necessary.
6349 Variable::determine_type()
6351 if (this->determined_type_
)
6353 this->determined_type_
= true;
6355 if (this->preinit_
!= NULL
)
6356 this->preinit_
->determine_types();
6358 // A variable in a type switch with a nil case will have the wrong
6359 // type here. It will have an initializer which is a type guard.
6360 // We want to initialize it to the value without the type guard, and
6361 // use the type of that value as well.
6362 if (this->is_type_switch_var_
6363 && this->type_
!= NULL
6364 && this->type_
->is_nil_constant_as_type())
6366 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6367 go_assert(tge
!= NULL
);
6369 this->init_
= tge
->expr();
6372 if (this->init_
== NULL
)
6373 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
6374 else if (this->type_from_init_tuple_
)
6376 Expression
*init
= this->init_
;
6377 init
->determine_type_no_context();
6378 this->type_
= this->type_from_tuple(init
, true);
6381 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6383 Expression
* init
= this->init_
;
6384 init
->determine_type_no_context();
6385 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
6389 else if (this->type_from_chan_element_
)
6391 Expression
* init
= this->init_
;
6392 init
->determine_type_no_context();
6393 this->type_
= this->type_from_chan_element(init
, true);
6398 Type_context
context(this->type_
, false);
6399 this->init_
->determine_type(&context
);
6400 if (this->type_
== NULL
)
6402 Type
* type
= this->init_
->type();
6403 go_assert(type
!= NULL
);
6404 if (type
->is_abstract())
6405 type
= type
->make_non_abstract_type();
6407 if (type
->is_void_type())
6409 error_at(this->location_
, "variable has no type");
6410 type
= Type::make_error_type();
6412 else if (type
->is_nil_type())
6414 error_at(this->location_
, "variable defined to nil type");
6415 type
= Type::make_error_type();
6417 else if (type
->is_call_multiple_result_type())
6419 error_at(this->location_
,
6420 "single variable set to multiple-value function call");
6421 type
= Type::make_error_type();
6429 // Get the initial value of a variable. This does not
6430 // consider whether the variable is in the heap--it returns the
6431 // initial value as though it were always stored in the stack.
6434 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
6436 go_assert(this->preinit_
== NULL
);
6437 Location loc
= this->location();
6438 if (this->init_
== NULL
)
6440 go_assert(!this->is_parameter_
);
6441 if (this->is_global_
|| this->is_in_heap())
6443 Btype
* btype
= this->type()->get_backend(gogo
);
6444 return gogo
->backend()->zero_expression(btype
);
6448 Translate_context
context(gogo
, function
, NULL
, NULL
);
6449 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
6450 return init
->get_backend(&context
);
6454 // Get the initial value of a variable when a block is required.
6455 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6458 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
6459 Bvariable
* var_decl
)
6461 go_assert(this->preinit_
!= NULL
);
6463 // We want to add the variable assignment to the end of the preinit
6466 Translate_context
context(gogo
, function
, NULL
, NULL
);
6467 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
6469 // It's possible to have pre-init statements without an initializer
6470 // if the pre-init statements set the variable.
6471 Bstatement
* decl_init
= NULL
;
6472 if (this->init_
!= NULL
)
6474 if (var_decl
== NULL
)
6476 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
6477 decl_init
= gogo
->backend()->expression_statement(init_bexpr
);
6481 Location loc
= this->location();
6482 Expression
* val_expr
=
6483 Expression::make_cast(this->type(), this->init_
, loc
);
6484 Bexpression
* val
= val_expr
->get_backend(&context
);
6485 Bexpression
* var_ref
= gogo
->backend()->var_expression(var_decl
, loc
);
6486 decl_init
= gogo
->backend()->assignment_statement(var_ref
, val
, loc
);
6489 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
6490 if (decl_init
!= NULL
)
6491 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
6495 // Export the variable
6498 Variable::export_var(Export
* exp
, const std::string
& name
) const
6500 go_assert(this->is_global_
);
6501 exp
->write_c_string("var ");
6502 exp
->write_string(name
);
6503 exp
->write_c_string(" ");
6504 exp
->write_type(this->type());
6505 exp
->write_c_string(";\n");
6508 // Import a variable.
6511 Variable::import_var(Import
* imp
, std::string
* pname
, Type
** ptype
)
6513 imp
->require_c_string("var ");
6514 *pname
= imp
->read_identifier();
6515 imp
->require_c_string(" ");
6516 *ptype
= imp
->read_type();
6517 imp
->require_c_string(";\n");
6520 // Convert a variable to the backend representation.
6523 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6524 const Package
* package
, const std::string
& name
)
6526 if (this->backend_
== NULL
)
6528 Backend
* backend
= gogo
->backend();
6529 Type
* type
= this->type_
;
6530 if (type
->is_error_type()
6531 || (type
->is_undefined()
6532 && (!this->is_global_
|| package
== NULL
)))
6533 this->backend_
= backend
->error_variable();
6536 bool is_parameter
= this->is_parameter_
;
6537 if (this->is_receiver_
&& type
->points_to() == NULL
)
6538 is_parameter
= false;
6539 if (this->is_in_heap())
6541 is_parameter
= false;
6542 type
= Type::make_pointer_type(type
);
6545 std::string n
= Gogo::unpack_hidden_name(name
);
6546 Btype
* btype
= type
->get_backend(gogo
);
6549 if (Map_type::is_zero_value(this))
6550 bvar
= Map_type::backend_zero_value(gogo
);
6551 else if (this->is_global_
)
6552 bvar
= backend
->global_variable((package
== NULL
6553 ? gogo
->package_name()
6554 : package
->package_name()),
6556 ? gogo
->pkgpath_symbol()
6557 : package
->pkgpath_symbol()),
6561 Gogo::is_hidden_name(name
),
6562 this->in_unique_section_
,
6564 else if (function
== NULL
)
6566 go_assert(saw_errors());
6567 bvar
= backend
->error_variable();
6571 Bfunction
* bfunction
= function
->func_value()->get_decl();
6572 bool is_address_taken
= (this->is_non_escaping_address_taken_
6573 && !this->is_in_heap());
6574 if (this->is_closure())
6575 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
6577 else if (is_parameter
)
6578 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
6582 bvar
= backend
->local_variable(bfunction
, n
, btype
,
6586 this->backend_
= bvar
;
6589 return this->backend_
;
6592 // Class Result_variable.
6594 // Convert a result variable to the backend representation.
6597 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6598 const std::string
& name
)
6600 if (this->backend_
== NULL
)
6602 Backend
* backend
= gogo
->backend();
6603 Type
* type
= this->type_
;
6604 if (type
->is_error())
6605 this->backend_
= backend
->error_variable();
6608 if (this->is_in_heap())
6609 type
= Type::make_pointer_type(type
);
6610 Btype
* btype
= type
->get_backend(gogo
);
6611 Bfunction
* bfunction
= function
->func_value()->get_decl();
6612 std::string n
= Gogo::unpack_hidden_name(name
);
6613 bool is_address_taken
= (this->is_non_escaping_address_taken_
6614 && !this->is_in_heap());
6615 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
6620 return this->backend_
;
6623 // Class Named_constant.
6625 // Traverse the initializer expression.
6628 Named_constant::traverse_expression(Traverse
* traverse
)
6630 return Expression::traverse(&this->expr_
, traverse
);
6633 // Determine the type of the constant.
6636 Named_constant::determine_type()
6638 if (this->type_
!= NULL
)
6640 Type_context
context(this->type_
, false);
6641 this->expr_
->determine_type(&context
);
6645 // A constant may have an abstract type.
6646 Type_context
context(NULL
, true);
6647 this->expr_
->determine_type(&context
);
6648 this->type_
= this->expr_
->type();
6649 go_assert(this->type_
!= NULL
);
6653 // Indicate that we found and reported an error for this constant.
6656 Named_constant::set_error()
6658 this->type_
= Type::make_error_type();
6659 this->expr_
= Expression::make_error(this->location_
);
6662 // Export a constant.
6665 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
6667 exp
->write_c_string("const ");
6668 exp
->write_string(name
);
6669 exp
->write_c_string(" ");
6670 if (!this->type_
->is_abstract())
6672 exp
->write_type(this->type_
);
6673 exp
->write_c_string(" ");
6675 exp
->write_c_string("= ");
6676 this->expr()->export_expression(exp
);
6677 exp
->write_c_string(";\n");
6680 // Import a constant.
6683 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
6686 imp
->require_c_string("const ");
6687 *pname
= imp
->read_identifier();
6688 imp
->require_c_string(" ");
6689 if (imp
->peek_char() == '=')
6693 *ptype
= imp
->read_type();
6694 imp
->require_c_string(" ");
6696 imp
->require_c_string("= ");
6697 *pexpr
= Expression::import_expression(imp
);
6698 imp
->require_c_string(";\n");
6701 // Get the backend representation.
6704 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
6706 if (this->bconst_
== NULL
)
6708 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
6709 Type
* type
= this->type();
6710 Location loc
= this->location();
6712 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
6713 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
6714 if (type
!= NULL
&& type
->is_numeric_type())
6716 Btype
* btype
= type
->get_backend(gogo
);
6717 std::string name
= const_no
->get_id(gogo
);
6719 gogo
->backend()->named_constant_expression(btype
, name
,
6722 this->bconst_
= const_decl
;
6724 return this->bconst_
;
6730 Type_declaration::add_method(const std::string
& name
, Function
* function
)
6732 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
6733 this->methods_
.push_back(ret
);
6737 // Add a method declaration.
6740 Type_declaration::add_method_declaration(const std::string
& name
,
6742 Function_type
* type
,
6745 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
6747 this->methods_
.push_back(ret
);
6751 // Return whether any methods ere defined.
6754 Type_declaration::has_methods() const
6756 return !this->methods_
.empty();
6759 // Define methods for the real type.
6762 Type_declaration::define_methods(Named_type
* nt
)
6764 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
6765 p
!= this->methods_
.end();
6767 nt
->add_existing_method(*p
);
6770 // We are using the type. Return true if we should issue a warning.
6773 Type_declaration::using_type()
6775 bool ret
= !this->issued_warning_
;
6776 this->issued_warning_
= true;
6780 // Class Unknown_name.
6782 // Set the real named object.
6785 Unknown_name::set_real_named_object(Named_object
* no
)
6787 go_assert(this->real_named_object_
== NULL
);
6788 go_assert(!no
->is_unknown());
6789 this->real_named_object_
= no
;
6792 // Class Named_object.
6794 Named_object::Named_object(const std::string
& name
,
6795 const Package
* package
,
6796 Classification classification
)
6797 : name_(name
), package_(package
), classification_(classification
),
6798 is_redefinition_(false)
6800 if (Gogo::is_sink_name(name
))
6801 go_assert(classification
== NAMED_OBJECT_SINK
);
6804 // Make an unknown name. This is used by the parser. The name must
6805 // be resolved later. Unknown names are only added in the current
6809 Named_object::make_unknown_name(const std::string
& name
,
6812 Named_object
* named_object
= new Named_object(name
, NULL
,
6813 NAMED_OBJECT_UNKNOWN
);
6814 Unknown_name
* value
= new Unknown_name(location
);
6815 named_object
->u_
.unknown_value
= value
;
6816 return named_object
;
6822 Named_object::make_constant(const Typed_identifier
& tid
,
6823 const Package
* package
, Expression
* expr
,
6826 Named_object
* named_object
= new Named_object(tid
.name(), package
,
6827 NAMED_OBJECT_CONST
);
6828 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
6831 named_object
->u_
.const_value
= named_constant
;
6832 return named_object
;
6835 // Make a named type.
6838 Named_object::make_type(const std::string
& name
, const Package
* package
,
6839 Type
* type
, Location location
)
6841 Named_object
* named_object
= new Named_object(name
, package
,
6843 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
6844 named_object
->u_
.type_value
= named_type
;
6845 return named_object
;
6848 // Make a type declaration.
6851 Named_object::make_type_declaration(const std::string
& name
,
6852 const Package
* package
,
6855 Named_object
* named_object
= new Named_object(name
, package
,
6856 NAMED_OBJECT_TYPE_DECLARATION
);
6857 Type_declaration
* type_declaration
= new Type_declaration(location
);
6858 named_object
->u_
.type_declaration
= type_declaration
;
6859 return named_object
;
6865 Named_object::make_variable(const std::string
& name
, const Package
* package
,
6868 Named_object
* named_object
= new Named_object(name
, package
,
6870 named_object
->u_
.var_value
= variable
;
6871 return named_object
;
6874 // Make a result variable.
6877 Named_object::make_result_variable(const std::string
& name
,
6878 Result_variable
* result
)
6880 Named_object
* named_object
= new Named_object(name
, NULL
,
6881 NAMED_OBJECT_RESULT_VAR
);
6882 named_object
->u_
.result_var_value
= result
;
6883 return named_object
;
6886 // Make a sink. This is used for the special blank identifier _.
6889 Named_object::make_sink()
6891 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
6894 // Make a named function.
6897 Named_object::make_function(const std::string
& name
, const Package
* package
,
6900 Named_object
* named_object
= new Named_object(name
, package
,
6902 named_object
->u_
.func_value
= function
;
6903 return named_object
;
6906 // Make a function declaration.
6909 Named_object::make_function_declaration(const std::string
& name
,
6910 const Package
* package
,
6911 Function_type
* fntype
,
6914 Named_object
* named_object
= new Named_object(name
, package
,
6915 NAMED_OBJECT_FUNC_DECLARATION
);
6916 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
6917 named_object
->u_
.func_declaration_value
= func_decl
;
6918 return named_object
;
6924 Named_object::make_package(const std::string
& alias
, Package
* package
)
6926 Named_object
* named_object
= new Named_object(alias
, NULL
,
6927 NAMED_OBJECT_PACKAGE
);
6928 named_object
->u_
.package_value
= package
;
6929 return named_object
;
6932 // Return the name to use in an error message.
6935 Named_object::message_name() const
6937 if (this->package_
== NULL
)
6938 return Gogo::message_name(this->name_
);
6940 if (this->package_
->has_package_name())
6941 ret
= this->package_
->package_name();
6943 ret
= this->package_
->pkgpath();
6944 ret
= Gogo::message_name(ret
);
6946 ret
+= Gogo::message_name(this->name_
);
6950 // Set the type when a declaration is defined.
6953 Named_object::set_type_value(Named_type
* named_type
)
6955 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
6956 Type_declaration
* td
= this->u_
.type_declaration
;
6957 td
->define_methods(named_type
);
6959 Named_object
* in_function
= td
->in_function(&index
);
6960 if (in_function
!= NULL
)
6961 named_type
->set_in_function(in_function
, index
);
6963 this->classification_
= NAMED_OBJECT_TYPE
;
6964 this->u_
.type_value
= named_type
;
6967 // Define a function which was previously declared.
6970 Named_object::set_function_value(Function
* function
)
6972 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
6973 if (this->func_declaration_value()->has_descriptor())
6975 Expression
* descriptor
=
6976 this->func_declaration_value()->descriptor(NULL
, NULL
);
6977 function
->set_descriptor(descriptor
);
6979 this->classification_
= NAMED_OBJECT_FUNC
;
6980 // FIXME: We should free the old value.
6981 this->u_
.func_value
= function
;
6984 // Declare an unknown object as a type declaration.
6987 Named_object::declare_as_type()
6989 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
6990 Unknown_name
* unk
= this->u_
.unknown_value
;
6991 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
6992 this->u_
.type_declaration
= new Type_declaration(unk
->location());
6996 // Return the location of a named object.
6999 Named_object::location() const
7001 switch (this->classification_
)
7004 case NAMED_OBJECT_UNINITIALIZED
:
7007 case NAMED_OBJECT_ERRONEOUS
:
7008 return Linemap::unknown_location();
7010 case NAMED_OBJECT_UNKNOWN
:
7011 return this->unknown_value()->location();
7013 case NAMED_OBJECT_CONST
:
7014 return this->const_value()->location();
7016 case NAMED_OBJECT_TYPE
:
7017 return this->type_value()->location();
7019 case NAMED_OBJECT_TYPE_DECLARATION
:
7020 return this->type_declaration_value()->location();
7022 case NAMED_OBJECT_VAR
:
7023 return this->var_value()->location();
7025 case NAMED_OBJECT_RESULT_VAR
:
7026 return this->result_var_value()->location();
7028 case NAMED_OBJECT_SINK
:
7031 case NAMED_OBJECT_FUNC
:
7032 return this->func_value()->location();
7034 case NAMED_OBJECT_FUNC_DECLARATION
:
7035 return this->func_declaration_value()->location();
7037 case NAMED_OBJECT_PACKAGE
:
7038 return this->package_value()->location();
7042 // Export a named object.
7045 Named_object::export_named_object(Export
* exp
) const
7047 switch (this->classification_
)
7050 case NAMED_OBJECT_UNINITIALIZED
:
7051 case NAMED_OBJECT_UNKNOWN
:
7054 case NAMED_OBJECT_ERRONEOUS
:
7057 case NAMED_OBJECT_CONST
:
7058 this->const_value()->export_const(exp
, this->name_
);
7061 case NAMED_OBJECT_TYPE
:
7062 this->type_value()->export_named_type(exp
, this->name_
);
7065 case NAMED_OBJECT_TYPE_DECLARATION
:
7066 error_at(this->type_declaration_value()->location(),
7067 "attempt to export %<%s%> which was declared but not defined",
7068 this->message_name().c_str());
7071 case NAMED_OBJECT_FUNC_DECLARATION
:
7072 this->func_declaration_value()->export_func(exp
, this->name_
);
7075 case NAMED_OBJECT_VAR
:
7076 this->var_value()->export_var(exp
, this->name_
);
7079 case NAMED_OBJECT_RESULT_VAR
:
7080 case NAMED_OBJECT_SINK
:
7083 case NAMED_OBJECT_FUNC
:
7084 this->func_value()->export_func(exp
, this->name_
);
7089 // Convert a variable to the backend representation.
7092 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
7094 if (this->classification_
== NAMED_OBJECT_VAR
)
7095 return this->var_value()->get_backend_variable(gogo
, function
,
7096 this->package_
, this->name_
);
7097 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
7098 return this->result_var_value()->get_backend_variable(gogo
, function
,
7105 // Return the external identifier for this object.
7108 Named_object::get_id(Gogo
* gogo
)
7110 go_assert(!this->is_variable() && !this->is_result_variable());
7111 std::string decl_name
;
7112 if (this->is_function_declaration()
7113 && !this->func_declaration_value()->asm_name().empty())
7114 decl_name
= this->func_declaration_value()->asm_name();
7115 else if (this->is_type()
7116 && Linemap::is_predeclared_location(this->type_value()->location()))
7118 // We don't need the package name for builtin types.
7119 decl_name
= Gogo::unpack_hidden_name(this->name_
);
7123 std::string package_name
;
7124 if (this->package_
== NULL
)
7125 package_name
= gogo
->package_name();
7127 package_name
= this->package_
->package_name();
7129 // Note that this will be misleading if this is an unexported
7130 // method generated for an embedded imported type. In that case
7131 // the unexported method should have the package name of the
7132 // package from which it is imported, but we are going to give
7133 // it our package name. Fixing this would require knowing the
7134 // package name, but we only know the package path. It might be
7135 // better to use package paths here anyhow. This doesn't affect
7136 // the assembler code, because we always set that name in
7137 // Function::get_or_make_decl anyhow. FIXME.
7139 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
7141 Function_type
* fntype
;
7142 if (this->is_function())
7143 fntype
= this->func_value()->type();
7144 else if (this->is_function_declaration())
7145 fntype
= this->func_declaration_value()->type();
7148 if (fntype
!= NULL
&& fntype
->is_method())
7150 decl_name
.push_back('.');
7151 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
7154 if (this->is_type())
7157 const Named_object
* in_function
= this->type_value()->in_function(&index
);
7158 if (in_function
!= NULL
)
7160 decl_name
+= '$' + Gogo::unpack_hidden_name(in_function
->name());
7164 snprintf(buf
, sizeof buf
, "%u", index
);
7173 // Get the backend representation for this named object.
7176 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
7177 std::vector
<Btype
*>& type_decls
,
7178 std::vector
<Bfunction
*>& func_decls
)
7180 switch (this->classification_
)
7182 case NAMED_OBJECT_CONST
:
7183 if (!Gogo::is_erroneous_name(this->name_
))
7184 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
7187 case NAMED_OBJECT_TYPE
:
7189 Named_type
* named_type
= this->u_
.type_value
;
7190 if (!Gogo::is_erroneous_name(this->name_
))
7191 type_decls
.push_back(named_type
->get_backend(gogo
));
7193 // We need to produce a type descriptor for every named
7194 // type, and for a pointer to every named type, since
7195 // other files or packages might refer to them. We need
7196 // to do this even for hidden types, because they might
7197 // still be returned by some function. Simply calling the
7198 // type_descriptor method is enough to create the type
7199 // descriptor, even though we don't do anything with it.
7200 if (this->package_
== NULL
&& !saw_errors())
7203 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7204 named_type
->gc_symbol_pointer(gogo
);
7205 Type
* pn
= Type::make_pointer_type(named_type
);
7206 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7207 pn
->gc_symbol_pointer(gogo
);
7212 case NAMED_OBJECT_TYPE_DECLARATION
:
7213 error("reference to undefined type %qs",
7214 this->message_name().c_str());
7217 case NAMED_OBJECT_VAR
:
7218 case NAMED_OBJECT_RESULT_VAR
:
7219 case NAMED_OBJECT_SINK
:
7222 case NAMED_OBJECT_FUNC
:
7224 Function
* func
= this->u_
.func_value
;
7225 if (!Gogo::is_erroneous_name(this->name_
))
7226 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
7228 if (func
->block() != NULL
)
7229 func
->build(gogo
, this);
7233 case NAMED_OBJECT_ERRONEOUS
:
7243 Bindings::Bindings(Bindings
* enclosing
)
7244 : enclosing_(enclosing
), named_objects_(), bindings_()
7251 Bindings::clear_file_scope(Gogo
* gogo
)
7253 Contour::iterator p
= this->bindings_
.begin();
7254 while (p
!= this->bindings_
.end())
7257 if (p
->second
->package() != NULL
)
7259 else if (p
->second
->is_package())
7261 else if (p
->second
->is_function()
7262 && !p
->second
->func_value()->type()->is_method()
7263 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
7272 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
7273 p
= this->bindings_
.erase(p
);
7278 // Look up a symbol.
7281 Bindings::lookup(const std::string
& name
) const
7283 Contour::const_iterator p
= this->bindings_
.find(name
);
7284 if (p
!= this->bindings_
.end())
7285 return p
->second
->resolve();
7286 else if (this->enclosing_
!= NULL
)
7287 return this->enclosing_
->lookup(name
);
7292 // Look up a symbol locally.
7295 Bindings::lookup_local(const std::string
& name
) const
7297 Contour::const_iterator p
= this->bindings_
.find(name
);
7298 if (p
== this->bindings_
.end())
7303 // Remove an object from a set of bindings. This is used for a
7304 // special case in thunks for functions which call recover.
7307 Bindings::remove_binding(Named_object
* no
)
7309 Contour::iterator pb
= this->bindings_
.find(no
->name());
7310 go_assert(pb
!= this->bindings_
.end());
7311 this->bindings_
.erase(pb
);
7312 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
7313 pn
!= this->named_objects_
.end();
7318 this->named_objects_
.erase(pn
);
7325 // Add a method to the list of objects. This is not added to the
7326 // lookup table. This is so that we have a single list of objects
7327 // declared at the top level, which we walk through when it's time to
7328 // convert to trees.
7331 Bindings::add_method(Named_object
* method
)
7333 this->named_objects_
.push_back(method
);
7336 // Add a generic Named_object to a Contour.
7339 Bindings::add_named_object_to_contour(Contour
* contour
,
7340 Named_object
* named_object
)
7342 go_assert(named_object
== named_object
->resolve());
7343 const std::string
& name(named_object
->name());
7344 go_assert(!Gogo::is_sink_name(name
));
7346 std::pair
<Contour::iterator
, bool> ins
=
7347 contour
->insert(std::make_pair(name
, named_object
));
7350 // The name was already there.
7351 if (named_object
->package() != NULL
7352 && ins
.first
->second
->package() == named_object
->package()
7353 && (ins
.first
->second
->classification()
7354 == named_object
->classification()))
7356 // This is a second import of the same object.
7357 return ins
.first
->second
;
7359 ins
.first
->second
= this->new_definition(ins
.first
->second
,
7361 return ins
.first
->second
;
7365 // Don't push declarations on the list. We push them on when
7366 // and if we find the definitions. That way we genericize the
7367 // functions in order.
7368 if (!named_object
->is_type_declaration()
7369 && !named_object
->is_function_declaration()
7370 && !named_object
->is_unknown())
7371 this->named_objects_
.push_back(named_object
);
7372 return named_object
;
7376 // We had an existing named object OLD_OBJECT, and we've seen a new
7377 // one NEW_OBJECT with the same name. FIXME: This does not free the
7378 // new object when we don't need it.
7381 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
7383 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
7387 switch (old_object
->classification())
7390 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
7393 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7396 case Named_object::NAMED_OBJECT_UNKNOWN
:
7398 Named_object
* real
= old_object
->unknown_value()->real_named_object();
7400 return this->new_definition(real
, new_object
);
7401 go_assert(!new_object
->is_unknown());
7402 old_object
->unknown_value()->set_real_named_object(new_object
);
7403 if (!new_object
->is_type_declaration()
7404 && !new_object
->is_function_declaration())
7405 this->named_objects_
.push_back(new_object
);
7409 case Named_object::NAMED_OBJECT_CONST
:
7412 case Named_object::NAMED_OBJECT_TYPE
:
7413 if (new_object
->is_type_declaration())
7417 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7418 if (new_object
->is_type_declaration())
7420 if (new_object
->is_type())
7422 old_object
->set_type_value(new_object
->type_value());
7423 new_object
->type_value()->set_named_object(old_object
);
7424 this->named_objects_
.push_back(old_object
);
7429 case Named_object::NAMED_OBJECT_VAR
:
7430 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7431 // We have already given an error in the parser for cases where
7432 // one parameter or result variable redeclares another one.
7433 if ((new_object
->is_variable()
7434 && new_object
->var_value()->is_parameter())
7435 || new_object
->is_result_variable())
7439 case Named_object::NAMED_OBJECT_SINK
:
7442 case Named_object::NAMED_OBJECT_FUNC
:
7443 if (new_object
->is_function_declaration())
7445 if (!new_object
->func_declaration_value()->asm_name().empty())
7446 sorry("__asm__ for function definitions");
7447 Function_type
* old_type
= old_object
->func_value()->type();
7448 Function_type
* new_type
=
7449 new_object
->func_declaration_value()->type();
7450 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7455 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7457 if (new_object
->is_function())
7459 Function_type
* old_type
=
7460 old_object
->func_declaration_value()->type();
7461 Function_type
* new_type
= new_object
->func_value()->type();
7462 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7464 if (!old_object
->func_declaration_value()->asm_name().empty())
7465 sorry("__asm__ for function definitions");
7466 old_object
->set_function_value(new_object
->func_value());
7467 this->named_objects_
.push_back(old_object
);
7474 case Named_object::NAMED_OBJECT_PACKAGE
:
7478 std::string n
= old_object
->message_name();
7480 error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
7482 error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
7484 old_object
->set_is_redefinition();
7485 new_object
->set_is_redefinition();
7487 inform(old_object
->location(), "previous definition of %qs was here",
7493 // Add a named type.
7496 Bindings::add_named_type(Named_type
* named_type
)
7498 return this->add_named_object(named_type
->named_object());
7504 Bindings::add_function(const std::string
& name
, const Package
* package
,
7507 return this->add_named_object(Named_object::make_function(name
, package
,
7511 // Add a function declaration.
7514 Bindings::add_function_declaration(const std::string
& name
,
7515 const Package
* package
,
7516 Function_type
* type
,
7519 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
7521 return this->add_named_object(no
);
7524 // Define a type which was previously declared.
7527 Bindings::define_type(Named_object
* no
, Named_type
* type
)
7529 no
->set_type_value(type
);
7530 this->named_objects_
.push_back(no
);
7533 // Mark all local variables as used. This is used for some types of
7537 Bindings::mark_locals_used()
7539 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
7540 p
!= this->named_objects_
.end();
7542 if ((*p
)->is_variable())
7543 (*p
)->var_value()->set_is_used();
7546 // Traverse bindings.
7549 Bindings::traverse(Traverse
* traverse
, bool is_global
)
7551 unsigned int traverse_mask
= traverse
->traverse_mask();
7553 // We don't use an iterator because we permit the traversal to add
7554 // new global objects.
7555 const unsigned int e_or_t
= (Traverse::traverse_expressions
7556 | Traverse::traverse_types
);
7557 const unsigned int e_or_t_or_s
= (e_or_t
7558 | Traverse::traverse_statements
);
7559 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
7561 Named_object
* p
= this->named_objects_
[i
];
7562 int t
= TRAVERSE_CONTINUE
;
7563 switch (p
->classification())
7565 case Named_object::NAMED_OBJECT_CONST
:
7566 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
7567 t
= traverse
->constant(p
, is_global
);
7568 if (t
== TRAVERSE_CONTINUE
7569 && (traverse_mask
& e_or_t
) != 0)
7571 Type
* tc
= p
->const_value()->type();
7573 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
7574 return TRAVERSE_EXIT
;
7575 t
= p
->const_value()->traverse_expression(traverse
);
7579 case Named_object::NAMED_OBJECT_VAR
:
7580 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7581 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
7582 t
= traverse
->variable(p
);
7583 if (t
== TRAVERSE_CONTINUE
7584 && (traverse_mask
& e_or_t
) != 0)
7586 if (p
->is_result_variable()
7587 || p
->var_value()->has_type())
7589 Type
* tv
= (p
->is_variable()
7590 ? p
->var_value()->type()
7591 : p
->result_var_value()->type());
7593 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
7594 return TRAVERSE_EXIT
;
7597 if (t
== TRAVERSE_CONTINUE
7598 && (traverse_mask
& e_or_t_or_s
) != 0
7599 && p
->is_variable())
7600 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
7603 case Named_object::NAMED_OBJECT_FUNC
:
7604 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
7605 t
= traverse
->function(p
);
7607 if (t
== TRAVERSE_CONTINUE
7609 & (Traverse::traverse_variables
7610 | Traverse::traverse_constants
7611 | Traverse::traverse_functions
7612 | Traverse::traverse_blocks
7613 | Traverse::traverse_statements
7614 | Traverse::traverse_expressions
7615 | Traverse::traverse_types
)) != 0)
7616 t
= p
->func_value()->traverse(traverse
);
7619 case Named_object::NAMED_OBJECT_PACKAGE
:
7620 // These are traversed in Gogo::traverse.
7621 go_assert(is_global
);
7624 case Named_object::NAMED_OBJECT_TYPE
:
7625 if ((traverse_mask
& e_or_t
) != 0)
7626 t
= Type::traverse(p
->type_value(), traverse
);
7629 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7630 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7631 case Named_object::NAMED_OBJECT_UNKNOWN
:
7632 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7635 case Named_object::NAMED_OBJECT_SINK
:
7640 if (t
== TRAVERSE_EXIT
)
7641 return TRAVERSE_EXIT
;
7644 // If we need to traverse types, check the function declarations,
7645 // which have types. Also check any methods of a type declaration.
7646 if ((traverse_mask
& e_or_t
) != 0)
7648 for (Bindings::const_declarations_iterator p
=
7649 this->begin_declarations();
7650 p
!= this->end_declarations();
7653 if (p
->second
->is_function_declaration())
7655 if (Type::traverse(p
->second
->func_declaration_value()->type(),
7658 return TRAVERSE_EXIT
;
7660 else if (p
->second
->is_type_declaration())
7662 const std::vector
<Named_object
*>* methods
=
7663 p
->second
->type_declaration_value()->methods();
7664 for (std::vector
<Named_object
*>::const_iterator pm
=
7666 pm
!= methods
->end();
7669 Named_object
* no
= *pm
;
7671 if (no
->is_function())
7672 t
= no
->func_value()->type();
7673 else if (no
->is_function_declaration())
7674 t
= no
->func_declaration_value()->type();
7677 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
7678 return TRAVERSE_EXIT
;
7684 return TRAVERSE_CONTINUE
;
7689 // Clear any references to this label.
7694 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
7695 p
!= this->refs_
.end();
7698 this->refs_
.clear();
7701 // Get the backend representation for a label.
7704 Label::get_backend_label(Translate_context
* context
)
7706 if (this->blabel_
== NULL
)
7708 Function
* function
= context
->function()->func_value();
7709 Bfunction
* bfunction
= function
->get_decl();
7710 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
7713 return this->blabel_
;
7716 // Return an expression for the address of this label.
7719 Label::get_addr(Translate_context
* context
, Location location
)
7721 Blabel
* label
= this->get_backend_label(context
);
7722 return context
->backend()->label_address(label
, location
);
7725 // Return the dummy label that represents any instance of the blank label.
7728 Label::create_dummy_label()
7730 static Label
* dummy_label
;
7731 if (dummy_label
== NULL
)
7733 dummy_label
= new Label("_");
7734 dummy_label
->set_is_used();
7739 // Class Unnamed_label.
7741 // Get the backend representation for an unnamed label.
7744 Unnamed_label::get_blabel(Translate_context
* context
)
7746 if (this->blabel_
== NULL
)
7748 Function
* function
= context
->function()->func_value();
7749 Bfunction
* bfunction
= function
->get_decl();
7750 this->blabel_
= context
->backend()->label(bfunction
, "",
7753 return this->blabel_
;
7756 // Return a statement which defines this unnamed label.
7759 Unnamed_label::get_definition(Translate_context
* context
)
7761 Blabel
* blabel
= this->get_blabel(context
);
7762 return context
->backend()->label_definition_statement(blabel
);
7765 // Return a goto statement to this unnamed label.
7768 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
7770 Blabel
* blabel
= this->get_blabel(context
);
7771 return context
->backend()->goto_statement(blabel
, location
);
7776 Package::Package(const std::string
& pkgpath
,
7777 const std::string
& pkgpath_symbol
, Location location
)
7778 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
7779 package_name_(), bindings_(new Bindings(NULL
)),
7782 go_assert(!pkgpath
.empty());
7785 // Set the package name.
7788 Package::set_package_name(const std::string
& package_name
, Location location
)
7790 go_assert(!package_name
.empty());
7791 if (this->package_name_
.empty())
7792 this->package_name_
= package_name
;
7793 else if (this->package_name_
!= package_name
)
7795 "saw two different packages with the same package path %s: %s, %s",
7796 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
7797 package_name
.c_str());
7800 // Return the pkgpath symbol, which is a prefix for symbols defined in
7804 Package::pkgpath_symbol() const
7806 if (this->pkgpath_symbol_
.empty())
7807 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
7808 return this->pkgpath_symbol_
;
7811 // Set the package path symbol.
7814 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
7816 go_assert(!pkgpath_symbol
.empty());
7817 if (this->pkgpath_symbol_
.empty())
7818 this->pkgpath_symbol_
= pkgpath_symbol
;
7820 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
7823 // Note that symbol from this package was and qualified by ALIAS.
7826 Package::note_usage(const std::string
& alias
) const
7828 Aliases::const_iterator p
= this->aliases_
.find(alias
);
7829 go_assert(p
!= this->aliases_
.end());
7830 p
->second
->note_usage();
7833 // Forget a given usage. If forgetting this usage means this package becomes
7834 // unused, report that error.
7837 Package::forget_usage(Expression
* usage
) const
7839 if (this->fake_uses_
.empty())
7842 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
7843 go_assert(p
!= this->fake_uses_
.end());
7844 this->fake_uses_
.erase(p
);
7846 if (this->fake_uses_
.empty())
7847 error_at(this->location(), "imported and not used: %s",
7848 Gogo::message_name(this->package_name()).c_str());
7851 // Clear the used field for the next file. If the only usages of this package
7852 // are possibly fake, keep the fake usages for lowering.
7855 Package::clear_used()
7857 std::string dot_alias
= "." + this->package_name();
7858 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
7859 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
7860 this->fake_uses_
.clear();
7862 this->aliases_
.clear();
7866 Package::add_alias(const std::string
& alias
, Location location
)
7868 Aliases::const_iterator p
= this->aliases_
.find(alias
);
7869 if (p
== this->aliases_
.end())
7871 std::pair
<Aliases::iterator
, bool> ret
;
7872 ret
= this->aliases_
.insert(std::make_pair(alias
,
7873 new Package_alias(location
)));
7879 // Determine types of constants. Everything else in a package
7880 // (variables, function declarations) should already have a fixed
7881 // type. Constants may have abstract types.
7884 Package::determine_types()
7886 Bindings
* bindings
= this->bindings_
;
7887 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
7888 p
!= bindings
->end_definitions();
7891 if ((*p
)->is_const())
7892 (*p
)->const_value()->determine_type();
7900 Traverse::~Traverse()
7902 if (this->types_seen_
!= NULL
)
7903 delete this->types_seen_
;
7904 if (this->expressions_seen_
!= NULL
)
7905 delete this->expressions_seen_
;
7908 // Record that we are looking at a type, and return true if we have
7912 Traverse::remember_type(const Type
* type
)
7914 if (type
->is_error_type())
7916 go_assert((this->traverse_mask() & traverse_types
) != 0
7917 || (this->traverse_mask() & traverse_expressions
) != 0);
7918 // We mostly only have to remember named types. But it turns out
7919 // that an interface type can refer to itself without using a name
7920 // by relying on interface inheritance, as in
7921 // type I interface { F() interface{I} }
7922 if (type
->classification() != Type::TYPE_NAMED
7923 && type
->classification() != Type::TYPE_INTERFACE
)
7925 if (this->types_seen_
== NULL
)
7926 this->types_seen_
= new Types_seen();
7927 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
7931 // Record that we are looking at an expression, and return true if we
7932 // have already seen it.
7935 Traverse::remember_expression(const Expression
* expression
)
7937 go_assert((this->traverse_mask() & traverse_types
) != 0
7938 || (this->traverse_mask() & traverse_expressions
) != 0);
7939 if (this->expressions_seen_
== NULL
)
7940 this->expressions_seen_
= new Expressions_seen();
7941 std::pair
<Expressions_seen::iterator
, bool> ins
=
7942 this->expressions_seen_
->insert(expression
);
7946 // The default versions of these functions should never be called: the
7947 // traversal mask indicates which functions may be called.
7950 Traverse::variable(Named_object
*)
7956 Traverse::constant(Named_object
*, bool)
7962 Traverse::function(Named_object
*)
7968 Traverse::block(Block
*)
7974 Traverse::statement(Block
*, size_t*, Statement
*)
7980 Traverse::expression(Expression
**)
7986 Traverse::type(Type
*)
7991 // Class Statement_inserter.
7994 Statement_inserter::insert(Statement
* s
)
7996 if (this->block_
!= NULL
)
7998 go_assert(this->pindex_
!= NULL
);
7999 this->block_
->insert_statement_before(*this->pindex_
, s
);
8002 else if (this->var_
!= NULL
)
8003 this->var_
->add_preinit_statement(this->gogo_
, s
);
8005 go_assert(saw_errors());