1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
13 #include "statements.h"
14 #include "expressions.h"
24 Gogo::Gogo(Backend* backend, Linemap* linemap, int int_type_size,
30 globals_(new Bindings(NULL)),
32 imported_unsafe_(false),
40 unique_prefix_specified_(false),
43 specific_type_functions_(),
44 specific_type_functions_are_written_(false),
45 named_types_are_converted_(false)
47 const Location loc = Linemap::predeclared_location();
49 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
50 RUNTIME_TYPE_KIND_UINT8);
51 this->add_named_type(uint8_type);
52 this->add_named_type(Type::make_integer_type("uint16", true, 16,
53 RUNTIME_TYPE_KIND_UINT16));
54 this->add_named_type(Type::make_integer_type("uint32", true, 32,
55 RUNTIME_TYPE_KIND_UINT32));
56 this->add_named_type(Type::make_integer_type("uint64", true, 64,
57 RUNTIME_TYPE_KIND_UINT64));
59 this->add_named_type(Type::make_integer_type("int8", false, 8,
60 RUNTIME_TYPE_KIND_INT8));
61 this->add_named_type(Type::make_integer_type("int16", false, 16,
62 RUNTIME_TYPE_KIND_INT16));
63 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
64 RUNTIME_TYPE_KIND_INT32);
65 this->add_named_type(int32_type);
66 this->add_named_type(Type::make_integer_type("int64", false, 64,
67 RUNTIME_TYPE_KIND_INT64));
69 this->add_named_type(Type::make_float_type("float32", 32,
70 RUNTIME_TYPE_KIND_FLOAT32));
71 this->add_named_type(Type::make_float_type("float64", 64,
72 RUNTIME_TYPE_KIND_FLOAT64));
74 this->add_named_type(Type::make_complex_type("complex64", 64,
75 RUNTIME_TYPE_KIND_COMPLEX64));
76 this->add_named_type(Type::make_complex_type("complex128", 128,
77 RUNTIME_TYPE_KIND_COMPLEX128));
79 if (int_type_size < 32)
81 this->add_named_type(Type::make_integer_type("uint", true,
83 RUNTIME_TYPE_KIND_UINT));
84 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
85 RUNTIME_TYPE_KIND_INT);
86 this->add_named_type(int_type);
88 this->add_named_type(Type::make_integer_type("uintptr", true,
90 RUNTIME_TYPE_KIND_UINTPTR));
92 // "byte" is an alias for "uint8".
93 uint8_type->integer_type()->set_is_byte();
94 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
96 this->add_named_type(byte_type->type_value());
98 // "rune" is an alias for "int32".
99 int32_type->integer_type()->set_is_rune();
100 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
102 this->add_named_type(rune_type->type_value());
104 this->add_named_type(Type::make_named_bool_type());
106 this->add_named_type(Type::make_named_string_type());
108 // "error" is interface { Error() string }.
110 Typed_identifier_list *methods = new Typed_identifier_list;
111 Typed_identifier_list *results = new Typed_identifier_list;
112 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
113 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
114 methods->push_back(Typed_identifier("Error", method_type, loc));
115 Interface_type *error_iface = Type::make_interface_type(methods, loc);
116 error_iface->finalize_methods();
117 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
118 this->add_named_type(error_type);
121 this->globals_->add_constant(Typed_identifier("true",
122 Type::make_boolean_type(),
125 Expression::make_boolean(true, loc),
127 this->globals_->add_constant(Typed_identifier("false",
128 Type::make_boolean_type(),
131 Expression::make_boolean(false, loc),
134 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
137 Expression::make_nil(loc),
140 Type* abstract_int_type = Type::make_abstract_integer_type();
141 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
144 Expression::make_iota(),
147 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
148 new_type->set_is_varargs();
149 new_type->set_is_builtin();
150 this->globals_->add_function_declaration("new", NULL, new_type, loc);
152 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
153 make_type->set_is_varargs();
154 make_type->set_is_builtin();
155 this->globals_->add_function_declaration("make", NULL, make_type, loc);
157 Typed_identifier_list* len_result = new Typed_identifier_list();
158 len_result->push_back(Typed_identifier("", int_type, loc));
159 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
161 len_type->set_is_builtin();
162 this->globals_->add_function_declaration("len", NULL, len_type, loc);
164 Typed_identifier_list* cap_result = new Typed_identifier_list();
165 cap_result->push_back(Typed_identifier("", int_type, loc));
166 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
168 cap_type->set_is_builtin();
169 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
171 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
172 print_type->set_is_varargs();
173 print_type->set_is_builtin();
174 this->globals_->add_function_declaration("print", NULL, print_type, loc);
176 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
177 print_type->set_is_varargs();
178 print_type->set_is_builtin();
179 this->globals_->add_function_declaration("println", NULL, print_type, loc);
181 Type *empty = Type::make_empty_interface_type(loc);
182 Typed_identifier_list* panic_parms = new Typed_identifier_list();
183 panic_parms->push_back(Typed_identifier("e", empty, loc));
184 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
186 panic_type->set_is_builtin();
187 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
189 Typed_identifier_list* recover_result = new Typed_identifier_list();
190 recover_result->push_back(Typed_identifier("", empty, loc));
191 Function_type* recover_type = Type::make_function_type(NULL, NULL,
194 recover_type->set_is_builtin();
195 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
197 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 close_type->set_is_varargs();
199 close_type->set_is_builtin();
200 this->globals_->add_function_declaration("close", NULL, close_type, loc);
202 Typed_identifier_list* copy_result = new Typed_identifier_list();
203 copy_result->push_back(Typed_identifier("", int_type, loc));
204 Function_type* copy_type = Type::make_function_type(NULL, NULL,
206 copy_type->set_is_varargs();
207 copy_type->set_is_builtin();
208 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
210 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
211 append_type->set_is_varargs();
212 append_type->set_is_builtin();
213 this->globals_->add_function_declaration("append", NULL, append_type, loc);
215 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
216 complex_type->set_is_varargs();
217 complex_type->set_is_builtin();
218 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
220 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
221 real_type->set_is_varargs();
222 real_type->set_is_builtin();
223 this->globals_->add_function_declaration("real", NULL, real_type, loc);
225 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
226 imag_type->set_is_varargs();
227 imag_type->set_is_builtin();
228 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
230 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
231 delete_type->set_is_varargs();
232 delete_type->set_is_builtin();
233 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
236 // Munge name for use in an error message.
239 Gogo::message_name(const std::string& name)
241 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
244 // Get the package name.
247 Gogo::package_name() const
249 go_assert(this->package_ != NULL);
250 return this->package_->name();
253 // Set the package name.
256 Gogo::set_package_name(const std::string& package_name,
259 if (this->package_ != NULL && this->package_->name() != package_name)
261 error_at(location, "expected package %<%s%>",
262 Gogo::message_name(this->package_->name()).c_str());
266 // If the user did not specify a unique prefix, we always use "go".
267 // This in effect requires that the package name be unique.
268 if (this->unique_prefix_.empty())
269 this->unique_prefix_ = "go";
271 this->package_ = this->register_package(package_name, this->unique_prefix_,
274 // We used to permit people to qualify symbols with the current
275 // package name (e.g., P.x), but we no longer do.
276 // this->globals_->add_package(package_name, this->package_);
278 if (this->is_main_package())
280 // Declare "main" as a function which takes no parameters and
282 Location uloc = Linemap::unknown_location();
283 this->declare_function("main",
284 Type::make_function_type (NULL, NULL, NULL, uloc),
289 // Return whether this is the "main" package. This is not true if
290 // -fgo-prefix was used.
293 Gogo::is_main_package() const
295 return this->package_name() == "main" && !this->unique_prefix_specified_;
301 Gogo::import_package(const std::string& filename,
302 const std::string& local_name,
303 bool is_local_name_exported,
306 if (filename == "unsafe")
308 this->import_unsafe(local_name, is_local_name_exported, location);
312 Imports::const_iterator p = this->imports_.find(filename);
313 if (p != this->imports_.end())
315 Package* package = p->second;
316 package->set_location(location);
317 package->set_is_imported();
318 std::string ln = local_name;
319 bool is_ln_exported = is_local_name_exported;
322 ln = package->name();
323 is_ln_exported = Lex::is_exported_name(ln);
327 Bindings* bindings = package->bindings();
328 for (Bindings::const_declarations_iterator p =
329 bindings->begin_declarations();
330 p != bindings->end_declarations();
332 this->add_named_object(p->second);
335 package->set_uses_sink_alias();
338 ln = this->pack_hidden_name(ln, is_ln_exported);
339 this->package_->bindings()->add_package(ln, package);
344 Import::Stream* stream = Import::open_package(filename, location);
347 error_at(location, "import file %qs not found", filename.c_str());
351 Import imp(stream, location);
352 imp.register_builtin_types(this);
353 Package* package = imp.import(this, local_name, is_local_name_exported);
356 if (package->name() == this->package_name()
357 && package->unique_prefix() == this->unique_prefix())
359 ("imported package uses same package name and prefix "
360 "as package being compiled (see -fgo-prefix option)"));
362 this->imports_.insert(std::make_pair(filename, package));
363 package->set_is_imported();
369 // Add an import control function for an imported package to the list.
372 Gogo::add_import_init_fn(const std::string& package_name,
373 const std::string& init_name, int prio)
375 for (std::set<Import_init>::const_iterator p =
376 this->imported_init_fns_.begin();
377 p != this->imported_init_fns_.end();
380 if (p->init_name() == init_name
381 && (p->package_name() != package_name || p->priority() != prio))
383 error("duplicate package initialization name %qs",
384 Gogo::message_name(init_name).c_str());
385 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
386 Gogo::message_name(p->package_name()).c_str(),
388 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
389 Gogo::message_name(package_name).c_str(), prio);
394 this->imported_init_fns_.insert(Import_init(package_name, init_name,
398 // Return whether we are at the global binding level.
401 Gogo::in_global_scope() const
403 return this->functions_.empty();
406 // Return the current binding contour.
409 Gogo::current_bindings()
411 if (!this->functions_.empty())
412 return this->functions_.back().blocks.back()->bindings();
413 else if (this->package_ != NULL)
414 return this->package_->bindings();
416 return this->globals_;
420 Gogo::current_bindings() const
422 if (!this->functions_.empty())
423 return this->functions_.back().blocks.back()->bindings();
424 else if (this->package_ != NULL)
425 return this->package_->bindings();
427 return this->globals_;
430 // Return the current block.
433 Gogo::current_block()
435 if (this->functions_.empty())
438 return this->functions_.back().blocks.back();
441 // Look up a name in the current binding contour. If PFUNCTION is not
442 // NULL, set it to the function in which the name is defined, or NULL
443 // if the name is defined in global scope.
446 Gogo::lookup(const std::string& name, Named_object** pfunction) const
448 if (pfunction != NULL)
451 if (Gogo::is_sink_name(name))
452 return Named_object::make_sink();
454 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
455 p != this->functions_.rend();
458 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
461 if (pfunction != NULL)
462 *pfunction = p->function;
467 if (this->package_ != NULL)
469 Named_object* ret = this->package_->bindings()->lookup(name);
472 if (ret->package() != NULL)
473 ret->package()->set_used();
478 // We do not look in the global namespace. If we did, the global
479 // namespace would effectively hide names which were defined in
480 // package scope which we have not yet seen. Instead,
481 // define_global_names is called after parsing is over to connect
482 // undefined names at package scope with names defined at global
488 // Look up a name in the current block, without searching enclosing
492 Gogo::lookup_in_block(const std::string& name) const
494 go_assert(!this->functions_.empty());
495 go_assert(!this->functions_.back().blocks.empty());
496 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
499 // Look up a name in the global namespace.
502 Gogo::lookup_global(const char* name) const
504 return this->globals_->lookup(name);
507 // Add an imported package.
510 Gogo::add_imported_package(const std::string& real_name,
511 const std::string& alias_arg,
512 bool is_alias_exported,
513 const std::string& unique_prefix,
515 bool* padd_to_globals)
517 // FIXME: Now that we compile packages as a whole, should we permit
518 // importing the current package?
519 if (this->package_name() == real_name
520 && this->unique_prefix() == unique_prefix)
522 *padd_to_globals = false;
523 if (!alias_arg.empty() && alias_arg != ".")
525 std::string alias = this->pack_hidden_name(alias_arg,
527 this->package_->bindings()->add_package(alias, this->package_);
529 return this->package_;
531 else if (alias_arg == ".")
533 *padd_to_globals = true;
534 return this->register_package(real_name, unique_prefix, location);
536 else if (alias_arg == "_")
538 Package* ret = this->register_package(real_name, unique_prefix, location);
539 ret->set_uses_sink_alias();
544 *padd_to_globals = false;
545 std::string alias = alias_arg;
549 is_alias_exported = Lex::is_exported_name(alias);
551 alias = this->pack_hidden_name(alias, is_alias_exported);
552 Named_object* no = this->add_package(real_name, alias, unique_prefix,
554 if (!no->is_package())
556 return no->package_value();
563 Gogo::add_package(const std::string& real_name, const std::string& alias,
564 const std::string& unique_prefix, Location location)
566 go_assert(this->in_global_scope());
568 // Register the package. Note that we might have already seen it in
569 // an earlier import.
570 Package* package = this->register_package(real_name, unique_prefix, location);
572 return this->package_->bindings()->add_package(alias, package);
575 // Register a package. This package may or may not be imported. This
576 // returns the Package structure for the package, creating if it
580 Gogo::register_package(const std::string& package_name,
581 const std::string& unique_prefix,
584 go_assert(!unique_prefix.empty() && !package_name.empty());
585 std::string name = unique_prefix + '.' + package_name;
586 Package* package = NULL;
587 std::pair<Packages::iterator, bool> ins =
588 this->packages_.insert(std::make_pair(name, package));
591 // We have seen this package name before.
592 package = ins.first->second;
593 go_assert(package != NULL);
594 go_assert(package->name() == package_name
595 && package->unique_prefix() == unique_prefix);
596 if (Linemap::is_unknown_location(package->location()))
597 package->set_location(location);
601 // First time we have seen this package name.
602 package = new Package(package_name, unique_prefix, location);
603 go_assert(ins.first->second == NULL);
604 ins.first->second = package;
610 // Start compiling a function.
613 Gogo::start_function(const std::string& name, Function_type* type,
614 bool add_method_to_type, Location location)
616 bool at_top_level = this->functions_.empty();
618 Block* block = new Block(NULL, location);
620 Function* enclosing = (at_top_level
622 : this->functions_.back().function->func_value());
624 Function* function = new Function(type, enclosing, block, location);
626 if (type->is_method())
628 const Typed_identifier* receiver = type->receiver();
629 Variable* this_param = new Variable(receiver->type(), NULL, false,
630 true, true, location);
631 std::string rname = receiver->name();
632 if (rname.empty() || Gogo::is_sink_name(rname))
634 // We need to give receivers a name since they wind up in
635 // DECL_ARGUMENTS. FIXME.
636 static unsigned int count;
638 snprintf(buf, sizeof buf, "r.%u", count);
642 block->bindings()->add_variable(rname, NULL, this_param);
645 const Typed_identifier_list* parameters = type->parameters();
646 bool is_varargs = type->is_varargs();
647 if (parameters != NULL)
649 for (Typed_identifier_list::const_iterator p = parameters->begin();
650 p != parameters->end();
653 Variable* param = new Variable(p->type(), NULL, false, true, false,
655 if (is_varargs && p + 1 == parameters->end())
656 param->set_is_varargs_parameter();
658 std::string pname = p->name();
659 if (pname.empty() || Gogo::is_sink_name(pname))
661 // We need to give parameters a name since they wind up
662 // in DECL_ARGUMENTS. FIXME.
663 static unsigned int count;
665 snprintf(buf, sizeof buf, "p.%u", count);
669 block->bindings()->add_variable(pname, NULL, param);
673 function->create_result_variables(this);
675 const std::string* pname;
676 std::string nested_name;
677 bool is_init = false;
678 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
680 if ((type->parameters() != NULL && !type->parameters()->empty())
681 || (type->results() != NULL && !type->results()->empty()))
683 "func init must have no arguments and no return values");
684 // There can be multiple "init" functions, so give them each a
686 static int init_count;
688 snprintf(buf, sizeof buf, ".$init%d", init_count);
691 pname = &nested_name;
694 else if (!name.empty())
698 // Invent a name for a nested function.
699 static int nested_count;
701 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
704 pname = &nested_name;
708 if (Gogo::is_sink_name(*pname))
710 static int sink_count;
712 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
714 ret = Named_object::make_function(buf, NULL, function);
716 else if (!type->is_method())
718 ret = this->package_->bindings()->add_function(*pname, NULL, function);
719 if (!ret->is_function() || ret->func_value() != function)
721 // Redefinition error. Invent a name to avoid knockon
723 static int redefinition_count;
725 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
726 ++redefinition_count;
727 ret = this->package_->bindings()->add_function(buf, NULL, function);
732 if (!add_method_to_type)
733 ret = Named_object::make_function(name, NULL, function);
736 go_assert(at_top_level);
737 Type* rtype = type->receiver()->type();
739 // We want to look through the pointer created by the
740 // parser, without getting an error if the type is not yet
742 if (rtype->classification() == Type::TYPE_POINTER)
743 rtype = rtype->points_to();
745 if (rtype->is_error_type())
746 ret = Named_object::make_function(name, NULL, function);
747 else if (rtype->named_type() != NULL)
749 ret = rtype->named_type()->add_method(name, function);
750 if (!ret->is_function())
752 // Redefinition error.
753 ret = Named_object::make_function(name, NULL, function);
756 else if (rtype->forward_declaration_type() != NULL)
758 Named_object* type_no =
759 rtype->forward_declaration_type()->named_object();
760 if (type_no->is_unknown())
762 // If we are seeing methods it really must be a
763 // type. Declare it as such. An alternative would
764 // be to support lists of methods for unknown
765 // expressions. Either way the error messages if
766 // this is not a type are going to get confusing.
767 Named_object* declared =
768 this->declare_package_type(type_no->name(),
769 type_no->location());
771 == type_no->unknown_value()->real_named_object());
773 ret = rtype->forward_declaration_type()->add_method(name,
779 this->package_->bindings()->add_method(ret);
782 this->functions_.resize(this->functions_.size() + 1);
783 Open_function& of(this->functions_.back());
785 of.blocks.push_back(block);
789 this->init_functions_.push_back(ret);
790 this->need_init_fn_ = true;
796 // Finish compiling a function.
799 Gogo::finish_function(Location location)
801 this->finish_block(location);
802 go_assert(this->functions_.back().blocks.empty());
803 this->functions_.pop_back();
806 // Return the current function.
809 Gogo::current_function() const
811 go_assert(!this->functions_.empty());
812 return this->functions_.back().function;
815 // Start a new block.
818 Gogo::start_block(Location location)
820 go_assert(!this->functions_.empty());
821 Block* block = new Block(this->current_block(), location);
822 this->functions_.back().blocks.push_back(block);
828 Gogo::finish_block(Location location)
830 go_assert(!this->functions_.empty());
831 go_assert(!this->functions_.back().blocks.empty());
832 Block* block = this->functions_.back().blocks.back();
833 this->functions_.back().blocks.pop_back();
834 block->set_end_location(location);
838 // Add an erroneous name.
841 Gogo::add_erroneous_name(const std::string& name)
843 return this->package_->bindings()->add_erroneous_name(name);
846 // Add an unknown name.
849 Gogo::add_unknown_name(const std::string& name, Location location)
851 return this->package_->bindings()->add_unknown_name(name, location);
854 // Declare a function.
857 Gogo::declare_function(const std::string& name, Function_type* type,
860 if (!type->is_method())
861 return this->current_bindings()->add_function_declaration(name, NULL, type,
865 // We don't bother to add this to the list of global
867 Type* rtype = type->receiver()->type();
869 // We want to look through the pointer created by the
870 // parser, without getting an error if the type is not yet
872 if (rtype->classification() == Type::TYPE_POINTER)
873 rtype = rtype->points_to();
875 if (rtype->is_error_type())
877 else if (rtype->named_type() != NULL)
878 return rtype->named_type()->add_method_declaration(name, NULL, type,
880 else if (rtype->forward_declaration_type() != NULL)
882 Forward_declaration_type* ftype = rtype->forward_declaration_type();
883 return ftype->add_method_declaration(name, NULL, type, location);
890 // Add a label definition.
893 Gogo::add_label_definition(const std::string& label_name,
896 go_assert(!this->functions_.empty());
897 Function* func = this->functions_.back().function->func_value();
898 Label* label = func->add_label_definition(this, label_name, location);
899 this->add_statement(Statement::make_label_statement(label, location));
903 // Add a label reference.
906 Gogo::add_label_reference(const std::string& label_name,
907 Location location, bool issue_goto_errors)
909 go_assert(!this->functions_.empty());
910 Function* func = this->functions_.back().function->func_value();
911 return func->add_label_reference(this, label_name, location,
915 // Return the current binding state.
918 Gogo::bindings_snapshot(Location location)
920 return new Bindings_snapshot(this->current_block(), location);
926 Gogo::add_statement(Statement* statement)
928 go_assert(!this->functions_.empty()
929 && !this->functions_.back().blocks.empty());
930 this->functions_.back().blocks.back()->add_statement(statement);
936 Gogo::add_block(Block* block, Location location)
938 go_assert(!this->functions_.empty()
939 && !this->functions_.back().blocks.empty());
940 Statement* statement = Statement::make_block_statement(block, location);
941 this->functions_.back().blocks.back()->add_statement(statement);
947 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
950 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
956 Gogo::add_type(const std::string& name, Type* type, Location location)
958 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
960 if (!this->in_global_scope() && no->is_type())
961 no->type_value()->set_in_function(this->functions_.back().function);
967 Gogo::add_named_type(Named_type* type)
969 go_assert(this->in_global_scope());
970 this->current_bindings()->add_named_type(type);
976 Gogo::declare_type(const std::string& name, Location location)
978 Bindings* bindings = this->current_bindings();
979 Named_object* no = bindings->add_type_declaration(name, NULL, location);
980 if (!this->in_global_scope() && no->is_type_declaration())
982 Named_object* f = this->functions_.back().function;
983 no->type_declaration_value()->set_in_function(f);
988 // Declare a type at the package level.
991 Gogo::declare_package_type(const std::string& name, Location location)
993 return this->package_->bindings()->add_type_declaration(name, NULL, location);
996 // Declare a function at the package level.
999 Gogo::declare_package_function(const std::string& name, Function_type* type,
1002 return this->package_->bindings()->add_function_declaration(name, NULL, type,
1006 // Define a type which was already declared.
1009 Gogo::define_type(Named_object* no, Named_type* type)
1011 this->current_bindings()->define_type(no, type);
1017 Gogo::add_variable(const std::string& name, Variable* variable)
1019 Named_object* no = this->current_bindings()->add_variable(name, NULL,
1022 // In a function the middle-end wants to see a DECL_EXPR node.
1024 && no->is_variable()
1025 && !no->var_value()->is_parameter()
1026 && !this->functions_.empty())
1027 this->add_statement(Statement::make_variable_declaration(no));
1032 // Add a sink--a reference to the blank identifier _.
1037 return Named_object::make_sink();
1040 // Add a named object.
1043 Gogo::add_named_object(Named_object* no)
1045 this->current_bindings()->add_named_object(no);
1048 // Mark all local variables used. This is used when some types of
1049 // parse error occur.
1052 Gogo::mark_locals_used()
1054 for (Open_functions::iterator pf = this->functions_.begin();
1055 pf != this->functions_.end();
1058 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
1059 pb != pf->blocks.end();
1061 (*pb)->bindings()->mark_locals_used();
1065 // Record that we've seen an interface type.
1068 Gogo::record_interface_type(Interface_type* itype)
1070 this->interface_types_.push_back(itype);
1073 // Return a name for a thunk object.
1078 static int thunk_count;
1079 char thunk_name[50];
1080 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1085 // Return whether a function is a thunk.
1088 Gogo::is_thunk(const Named_object* no)
1090 return no->name().compare(0, 6, "$thunk") == 0;
1093 // Define the global names. We do this only after parsing all the
1094 // input files, because the program might define the global names
1098 Gogo::define_global_names()
1100 for (Bindings::const_declarations_iterator p =
1101 this->globals_->begin_declarations();
1102 p != this->globals_->end_declarations();
1105 Named_object* global_no = p->second;
1106 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1107 Named_object* no = this->package_->bindings()->lookup(name);
1111 if (no->is_type_declaration())
1113 if (global_no->is_type())
1115 if (no->type_declaration_value()->has_methods())
1116 error_at(no->location(),
1117 "may not define methods for global type");
1118 no->set_type_value(global_no->type_value());
1122 error_at(no->location(), "expected type");
1123 Type* errtype = Type::make_error_type();
1125 Named_object::make_type("erroneous_type", NULL, errtype,
1126 Linemap::predeclared_location());
1127 no->set_type_value(err->type_value());
1130 else if (no->is_unknown())
1131 no->unknown_value()->set_real_named_object(global_no);
1135 // Clear out names in file scope.
1138 Gogo::clear_file_scope()
1140 this->package_->bindings()->clear_file_scope();
1142 // Warn about packages which were imported but not used.
1143 for (Packages::iterator p = this->packages_.begin();
1144 p != this->packages_.end();
1147 Package* package = p->second;
1148 if (package != this->package_
1149 && package->is_imported()
1151 && !package->uses_sink_alias()
1153 error_at(package->location(), "imported and not used: %s",
1154 Gogo::message_name(package->name()).c_str());
1155 package->clear_is_imported();
1156 package->clear_uses_sink_alias();
1157 package->clear_used();
1161 // Queue up a type specific function for later writing. These are
1162 // written out in write_specific_type_functions, called after the
1163 // parse tree is lowered.
1166 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1167 const std::string& hash_name,
1168 Function_type* hash_fntype,
1169 const std::string& equal_name,
1170 Function_type* equal_fntype)
1172 go_assert(!this->specific_type_functions_are_written_);
1173 go_assert(!this->in_global_scope());
1174 Specific_type_function* tsf = new Specific_type_function(type, name,
1179 this->specific_type_functions_.push_back(tsf);
1182 // Look for types which need specific hash or equality functions.
1184 class Specific_type_functions : public Traverse
1187 Specific_type_functions(Gogo* gogo)
1188 : Traverse(traverse_types),
1200 Specific_type_functions::type(Type* t)
1202 Named_object* hash_fn;
1203 Named_object* equal_fn;
1204 switch (t->classification())
1206 case Type::TYPE_NAMED:
1208 Named_type* nt = t->named_type();
1209 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1210 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
1212 // If this is a struct type, we don't want to make functions
1213 // for the unnamed struct.
1214 Type* rt = nt->real_type();
1215 if (rt->struct_type() == NULL)
1217 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1218 return TRAVERSE_EXIT;
1222 // If this type is defined in another package, then we don't
1223 // need to worry about the unexported fields.
1224 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
1225 const Struct_field_list* fields = rt->struct_type()->fields();
1226 for (Struct_field_list::const_iterator p = fields->begin();
1230 if (is_defined_elsewhere
1231 && Gogo::is_hidden_name(p->field_name()))
1233 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
1234 return TRAVERSE_EXIT;
1238 return TRAVERSE_SKIP_COMPONENTS;
1241 case Type::TYPE_STRUCT:
1242 case Type::TYPE_ARRAY:
1243 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1244 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1251 return TRAVERSE_CONTINUE;
1254 // Write out type specific functions.
1257 Gogo::write_specific_type_functions()
1259 Specific_type_functions stf(this);
1260 this->traverse(&stf);
1262 while (!this->specific_type_functions_.empty())
1264 Specific_type_function* tsf = this->specific_type_functions_.back();
1265 this->specific_type_functions_.pop_back();
1266 tsf->type->write_specific_type_functions(this, tsf->name,
1273 this->specific_type_functions_are_written_ = true;
1276 // Traverse the tree.
1279 Gogo::traverse(Traverse* traverse)
1281 // Traverse the current package first for consistency. The other
1282 // packages will only contain imported types, constants, and
1284 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1286 for (Packages::const_iterator p = this->packages_.begin();
1287 p != this->packages_.end();
1290 if (p->second != this->package_)
1292 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1298 // Add a type to verify. This is used for types of sink variables, in
1299 // order to give appropriate error messages.
1302 Gogo::add_type_to_verify(Type* type)
1304 this->verify_types_.push_back(type);
1307 // Traversal class used to verify types.
1309 class Verify_types : public Traverse
1313 : Traverse(traverse_types)
1320 // Verify that a type is correct.
1323 Verify_types::type(Type* t)
1326 return TRAVERSE_SKIP_COMPONENTS;
1327 return TRAVERSE_CONTINUE;
1330 // Verify that all types are correct.
1333 Gogo::verify_types()
1335 Verify_types traverse;
1336 this->traverse(&traverse);
1338 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
1339 p != this->verify_types_.end();
1342 this->verify_types_.clear();
1345 // Traversal class used to lower parse tree.
1347 class Lower_parse_tree : public Traverse
1350 Lower_parse_tree(Gogo* gogo, Named_object* function)
1351 : Traverse(traverse_variables
1352 | traverse_constants
1353 | traverse_functions
1354 | traverse_statements
1355 | traverse_expressions),
1356 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1360 set_inserter(const Statement_inserter* inserter)
1361 { this->inserter_ = *inserter; }
1364 variable(Named_object*);
1367 constant(Named_object*, bool);
1370 function(Named_object*);
1373 statement(Block*, size_t* pindex, Statement*);
1376 expression(Expression**);
1381 // The function we are traversing.
1382 Named_object* function_;
1383 // Value to use for the predeclared constant iota.
1385 // Current statement inserter for use by expressions.
1386 Statement_inserter inserter_;
1392 Lower_parse_tree::variable(Named_object* no)
1394 if (!no->is_variable())
1395 return TRAVERSE_CONTINUE;
1397 if (no->is_variable() && no->var_value()->is_global())
1399 // Global variables can have loops in their initialization
1400 // expressions. This is handled in lower_init_expression.
1401 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1403 return TRAVERSE_CONTINUE;
1406 // This is a local variable. We are going to return
1407 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1408 // initialization expression when we reach the variable declaration
1409 // statement. However, that means that we need to traverse the type
1411 if (no->var_value()->has_type())
1413 Type* type = no->var_value()->type();
1416 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1417 return TRAVERSE_EXIT;
1420 go_assert(!no->var_value()->has_pre_init());
1422 return TRAVERSE_SKIP_COMPONENTS;
1425 // Lower constants. We handle constants specially so that we can set
1426 // the right value for the predeclared constant iota. This works in
1427 // conjunction with the way we lower Const_expression objects.
1430 Lower_parse_tree::constant(Named_object* no, bool)
1432 Named_constant* nc = no->const_value();
1434 // Don't get into trouble if the constant's initializer expression
1435 // refers to the constant itself.
1437 return TRAVERSE_CONTINUE;
1440 go_assert(this->iota_value_ == -1);
1441 this->iota_value_ = nc->iota_value();
1442 nc->traverse_expression(this);
1443 this->iota_value_ = -1;
1445 nc->clear_lowering();
1447 // We will traverse the expression a second time, but that will be
1450 return TRAVERSE_CONTINUE;
1453 // Lower function closure types. Record the function while lowering
1454 // it, so that we can pass it down when lowering an expression.
1457 Lower_parse_tree::function(Named_object* no)
1459 no->func_value()->set_closure_type();
1461 go_assert(this->function_ == NULL);
1462 this->function_ = no;
1463 int t = no->func_value()->traverse(this);
1464 this->function_ = NULL;
1466 if (t == TRAVERSE_EXIT)
1468 return TRAVERSE_SKIP_COMPONENTS;
1471 // Lower statement parse trees.
1474 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1476 // Because we explicitly traverse the statement's contents
1477 // ourselves, we want to skip block statements here. There is
1478 // nothing to lower in a block statement.
1479 if (sorig->is_block_statement())
1480 return TRAVERSE_CONTINUE;
1482 Statement_inserter hold_inserter(this->inserter_);
1483 this->inserter_ = Statement_inserter(block, pindex);
1485 // Lower the expressions first.
1486 int t = sorig->traverse_contents(this);
1487 if (t == TRAVERSE_EXIT)
1489 this->inserter_ = hold_inserter;
1493 // Keep lowering until nothing changes.
1494 Statement* s = sorig;
1497 Statement* snew = s->lower(this->gogo_, this->function_, block,
1502 t = s->traverse_contents(this);
1503 if (t == TRAVERSE_EXIT)
1505 this->inserter_ = hold_inserter;
1511 block->replace_statement(*pindex, s);
1513 this->inserter_ = hold_inserter;
1514 return TRAVERSE_SKIP_COMPONENTS;
1517 // Lower expression parse trees.
1520 Lower_parse_tree::expression(Expression** pexpr)
1522 // We have to lower all subexpressions first, so that we can get
1523 // their type if necessary. This is awkward, because we don't have
1524 // a postorder traversal pass.
1525 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1526 return TRAVERSE_EXIT;
1527 // Keep lowering until nothing changes.
1530 Expression* e = *pexpr;
1531 Expression* enew = e->lower(this->gogo_, this->function_,
1532 &this->inserter_, this->iota_value_);
1535 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
1536 return TRAVERSE_EXIT;
1539 return TRAVERSE_SKIP_COMPONENTS;
1542 // Lower the parse tree. This is called after the parse is complete,
1543 // when all names should be resolved.
1546 Gogo::lower_parse_tree()
1548 Lower_parse_tree lower_parse_tree(this, NULL);
1549 this->traverse(&lower_parse_tree);
1555 Gogo::lower_block(Named_object* function, Block* block)
1557 Lower_parse_tree lower_parse_tree(this, function);
1558 block->traverse(&lower_parse_tree);
1561 // Lower an expression. INSERTER may be NULL, in which case the
1562 // expression had better not need to create any temporaries.
1565 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1568 Lower_parse_tree lower_parse_tree(this, function);
1569 if (inserter != NULL)
1570 lower_parse_tree.set_inserter(inserter);
1571 lower_parse_tree.expression(pexpr);
1574 // Lower a constant. This is called when lowering a reference to a
1575 // constant. We have to make sure that the constant has already been
1579 Gogo::lower_constant(Named_object* no)
1581 go_assert(no->is_const());
1582 Lower_parse_tree lower(this, NULL);
1583 lower.constant(no, false);
1586 // Look for interface types to finalize methods of inherited
1589 class Finalize_methods : public Traverse
1592 Finalize_methods(Gogo* gogo)
1593 : Traverse(traverse_types),
1604 // Finalize the methods of an interface type.
1607 Finalize_methods::type(Type* t)
1609 // Check the classification so that we don't finalize the methods
1610 // twice for a named interface type.
1611 switch (t->classification())
1613 case Type::TYPE_INTERFACE:
1614 t->interface_type()->finalize_methods();
1617 case Type::TYPE_NAMED:
1619 // We have to finalize the methods of the real type first.
1620 // But if the real type is a struct type, then we only want to
1621 // finalize the methods of the field types, not of the struct
1622 // type itself. We don't want to add methods to the struct,
1623 // since it has a name.
1624 Named_type* nt = t->named_type();
1625 Type* rt = nt->real_type();
1626 if (rt->classification() != Type::TYPE_STRUCT)
1628 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1629 return TRAVERSE_EXIT;
1633 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1634 return TRAVERSE_EXIT;
1637 nt->finalize_methods(this->gogo_);
1639 // If this type is defined in a different package, then finalize the
1640 // types of all the methods, since we won't see them otherwise.
1641 if (nt->named_object()->package() != NULL && nt->has_any_methods())
1643 const Methods* methods = nt->methods();
1644 for (Methods::const_iterator p = methods->begin();
1645 p != methods->end();
1648 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1649 return TRAVERSE_EXIT;
1653 return TRAVERSE_SKIP_COMPONENTS;
1656 case Type::TYPE_STRUCT:
1657 // Traverse the field types first in case there is an embedded
1658 // field with methods that the struct should inherit.
1659 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1660 return TRAVERSE_EXIT;
1661 t->struct_type()->finalize_methods(this->gogo_);
1662 return TRAVERSE_SKIP_COMPONENTS;
1668 return TRAVERSE_CONTINUE;
1671 // Finalize method lists and build stub methods for types.
1674 Gogo::finalize_methods()
1676 Finalize_methods finalize(this);
1677 this->traverse(&finalize);
1680 // Set types for unspecified variables and constants.
1683 Gogo::determine_types()
1685 Bindings* bindings = this->current_bindings();
1686 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1687 p != bindings->end_definitions();
1690 if ((*p)->is_function())
1691 (*p)->func_value()->determine_types();
1692 else if ((*p)->is_variable())
1693 (*p)->var_value()->determine_type();
1694 else if ((*p)->is_const())
1695 (*p)->const_value()->determine_type();
1697 // See if a variable requires us to build an initialization
1698 // function. We know that we will see all global variables
1700 if (!this->need_init_fn_ && (*p)->is_variable())
1702 Variable* variable = (*p)->var_value();
1704 // If this is a global variable which requires runtime
1705 // initialization, we need an initialization function.
1706 if (!variable->is_global())
1708 else if (variable->init() == NULL)
1710 else if (variable->type()->interface_type() != NULL)
1711 this->need_init_fn_ = true;
1712 else if (variable->init()->is_constant())
1714 else if (!variable->init()->is_composite_literal())
1715 this->need_init_fn_ = true;
1716 else if (variable->init()->is_nonconstant_composite_literal())
1717 this->need_init_fn_ = true;
1719 // If this is a global variable which holds a pointer value,
1720 // then we need an initialization function to register it as a
1722 if (variable->is_global() && variable->type()->has_pointer())
1723 this->need_init_fn_ = true;
1727 // Determine the types of constants in packages.
1728 for (Packages::const_iterator p = this->packages_.begin();
1729 p != this->packages_.end();
1731 p->second->determine_types();
1734 // Traversal class used for type checking.
1736 class Check_types_traverse : public Traverse
1739 Check_types_traverse(Gogo* gogo)
1740 : Traverse(traverse_variables
1741 | traverse_constants
1742 | traverse_functions
1743 | traverse_statements
1744 | traverse_expressions),
1749 variable(Named_object*);
1752 constant(Named_object*, bool);
1755 function(Named_object*);
1758 statement(Block*, size_t* pindex, Statement*);
1761 expression(Expression**);
1768 // Check that a variable initializer has the right type.
1771 Check_types_traverse::variable(Named_object* named_object)
1773 if (named_object->is_variable())
1775 Variable* var = named_object->var_value();
1777 // Give error if variable type is not defined.
1778 var->type()->base();
1780 Expression* init = var->init();
1783 && !Type::are_assignable(var->type(), init->type(), &reason))
1786 error_at(var->location(), "incompatible type in initialization");
1788 error_at(var->location(),
1789 "incompatible type in initialization (%s)",
1793 else if (!var->is_used()
1794 && !var->is_global()
1795 && !var->is_parameter()
1796 && !var->is_receiver()
1797 && !var->type()->is_error()
1798 && (init == NULL || !init->is_error_expression())
1799 && !Lex::is_invalid_identifier(named_object->name()))
1800 error_at(var->location(), "%qs declared and not used",
1801 named_object->message_name().c_str());
1803 return TRAVERSE_CONTINUE;
1806 // Check that a constant initializer has the right type.
1809 Check_types_traverse::constant(Named_object* named_object, bool)
1811 Named_constant* constant = named_object->const_value();
1812 Type* ctype = constant->type();
1813 if (ctype->integer_type() == NULL
1814 && ctype->float_type() == NULL
1815 && ctype->complex_type() == NULL
1816 && !ctype->is_boolean_type()
1817 && !ctype->is_string_type())
1819 if (ctype->is_nil_type())
1820 error_at(constant->location(), "const initializer cannot be nil");
1821 else if (!ctype->is_error())
1822 error_at(constant->location(), "invalid constant type");
1823 constant->set_error();
1825 else if (!constant->expr()->is_constant())
1827 error_at(constant->expr()->location(), "expression is not constant");
1828 constant->set_error();
1830 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1833 error_at(constant->location(),
1834 "initialization expression has wrong type");
1835 constant->set_error();
1837 return TRAVERSE_CONTINUE;
1840 // There are no types to check in a function, but this is where we
1841 // issue warnings about labels which are defined but not referenced.
1844 Check_types_traverse::function(Named_object* no)
1846 no->func_value()->check_labels();
1847 return TRAVERSE_CONTINUE;
1850 // Check that types are valid in a statement.
1853 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1855 s->check_types(this->gogo_);
1856 return TRAVERSE_CONTINUE;
1859 // Check that types are valid in an expression.
1862 Check_types_traverse::expression(Expression** expr)
1864 (*expr)->check_types(this->gogo_);
1865 return TRAVERSE_CONTINUE;
1868 // Check that types are valid.
1873 Check_types_traverse traverse(this);
1874 this->traverse(&traverse);
1877 // Check the types in a single block.
1880 Gogo::check_types_in_block(Block* block)
1882 Check_types_traverse traverse(this);
1883 block->traverse(&traverse);
1886 // A traversal class used to find a single shortcut operator within an
1889 class Find_shortcut : public Traverse
1893 : Traverse(traverse_blocks
1894 | traverse_statements
1895 | traverse_expressions),
1899 // A pointer to the expression which was found, or NULL if none was
1903 { return this->found_; }
1908 { return TRAVERSE_SKIP_COMPONENTS; }
1911 statement(Block*, size_t*, Statement*)
1912 { return TRAVERSE_SKIP_COMPONENTS; }
1915 expression(Expression**);
1918 Expression** found_;
1921 // Find a shortcut expression.
1924 Find_shortcut::expression(Expression** pexpr)
1926 Expression* expr = *pexpr;
1927 Binary_expression* be = expr->binary_expression();
1929 return TRAVERSE_CONTINUE;
1930 Operator op = be->op();
1931 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1932 return TRAVERSE_CONTINUE;
1933 go_assert(this->found_ == NULL);
1934 this->found_ = pexpr;
1935 return TRAVERSE_EXIT;
1938 // A traversal class used to turn shortcut operators into explicit if
1941 class Shortcuts : public Traverse
1944 Shortcuts(Gogo* gogo)
1945 : Traverse(traverse_variables
1946 | traverse_statements),
1952 variable(Named_object*);
1955 statement(Block*, size_t*, Statement*);
1958 // Convert a shortcut operator.
1960 convert_shortcut(Block* enclosing, Expression** pshortcut);
1966 // Remove shortcut operators in a single statement.
1969 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1971 // FIXME: This approach doesn't work for switch statements, because
1972 // we add the new statements before the whole switch when we need to
1973 // instead add them just before the switch expression. The right
1974 // fix is probably to lower switch statements with nonconstant cases
1975 // to a series of conditionals.
1976 if (s->switch_statement() != NULL)
1977 return TRAVERSE_CONTINUE;
1981 Find_shortcut find_shortcut;
1983 // If S is a variable declaration, then ordinary traversal won't
1984 // do anything. We want to explicitly traverse the
1985 // initialization expression if there is one.
1986 Variable_declaration_statement* vds = s->variable_declaration_statement();
1987 Expression* init = NULL;
1989 s->traverse_contents(&find_shortcut);
1992 init = vds->var()->var_value()->init();
1994 return TRAVERSE_CONTINUE;
1995 init->traverse(&init, &find_shortcut);
1997 Expression** pshortcut = find_shortcut.found();
1998 if (pshortcut == NULL)
1999 return TRAVERSE_CONTINUE;
2001 Statement* snew = this->convert_shortcut(block, pshortcut);
2002 block->insert_statement_before(*pindex, snew);
2005 if (pshortcut == &init)
2006 vds->var()->var_value()->set_init(init);
2010 // Remove shortcut operators in the initializer of a global variable.
2013 Shortcuts::variable(Named_object* no)
2015 if (no->is_result_variable())
2016 return TRAVERSE_CONTINUE;
2017 Variable* var = no->var_value();
2018 Expression* init = var->init();
2019 if (!var->is_global() || init == NULL)
2020 return TRAVERSE_CONTINUE;
2024 Find_shortcut find_shortcut;
2025 init->traverse(&init, &find_shortcut);
2026 Expression** pshortcut = find_shortcut.found();
2027 if (pshortcut == NULL)
2028 return TRAVERSE_CONTINUE;
2030 Statement* snew = this->convert_shortcut(NULL, pshortcut);
2031 var->add_preinit_statement(this->gogo_, snew);
2032 if (pshortcut == &init)
2033 var->set_init(init);
2037 // Given an expression which uses a shortcut operator, return a
2038 // statement which implements it, and update *PSHORTCUT accordingly.
2041 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2043 Binary_expression* shortcut = (*pshortcut)->binary_expression();
2044 Expression* left = shortcut->left();
2045 Expression* right = shortcut->right();
2046 Location loc = shortcut->location();
2048 Block* retblock = new Block(enclosing, loc);
2049 retblock->set_end_location(loc);
2051 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
2053 retblock->add_statement(ts);
2055 Block* block = new Block(retblock, loc);
2056 block->set_end_location(loc);
2057 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2058 Statement* assign = Statement::make_assignment(tmpref, right, loc);
2059 block->add_statement(assign);
2061 Expression* cond = Expression::make_temporary_reference(ts, loc);
2062 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2063 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2065 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2067 retblock->add_statement(if_statement);
2069 *pshortcut = Expression::make_temporary_reference(ts, loc);
2073 // Now convert any shortcut operators in LEFT and RIGHT.
2074 Shortcuts shortcuts(this->gogo_);
2075 retblock->traverse(&shortcuts);
2077 return Statement::make_block_statement(retblock, loc);
2080 // Turn shortcut operators into explicit if statements. Doing this
2081 // considerably simplifies the order of evaluation rules.
2084 Gogo::remove_shortcuts()
2086 Shortcuts shortcuts(this);
2087 this->traverse(&shortcuts);
2090 // A traversal class which finds all the expressions which must be
2091 // evaluated in order within a statement or larger expression. This
2092 // is used to implement the rules about order of evaluation.
2094 class Find_eval_ordering : public Traverse
2097 typedef std::vector<Expression**> Expression_pointers;
2100 Find_eval_ordering()
2101 : Traverse(traverse_blocks
2102 | traverse_statements
2103 | traverse_expressions),
2109 { return this->exprs_.size(); }
2111 typedef Expression_pointers::const_iterator const_iterator;
2115 { return this->exprs_.begin(); }
2119 { return this->exprs_.end(); }
2124 { return TRAVERSE_SKIP_COMPONENTS; }
2127 statement(Block*, size_t*, Statement*)
2128 { return TRAVERSE_SKIP_COMPONENTS; }
2131 expression(Expression**);
2134 // A list of pointers to expressions with side-effects.
2135 Expression_pointers exprs_;
2138 // If an expression must be evaluated in order, put it on the list.
2141 Find_eval_ordering::expression(Expression** expression_pointer)
2143 // We have to look at subexpressions before this one.
2144 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2145 return TRAVERSE_EXIT;
2146 if ((*expression_pointer)->must_eval_in_order())
2147 this->exprs_.push_back(expression_pointer);
2148 return TRAVERSE_SKIP_COMPONENTS;
2151 // A traversal class for ordering evaluations.
2153 class Order_eval : public Traverse
2156 Order_eval(Gogo* gogo)
2157 : Traverse(traverse_variables
2158 | traverse_statements),
2163 variable(Named_object*);
2166 statement(Block*, size_t*, Statement*);
2173 // Implement the order of evaluation rules for a statement.
2176 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2178 // FIXME: This approach doesn't work for switch statements, because
2179 // we add the new statements before the whole switch when we need to
2180 // instead add them just before the switch expression. The right
2181 // fix is probably to lower switch statements with nonconstant cases
2182 // to a series of conditionals.
2183 if (s->switch_statement() != NULL)
2184 return TRAVERSE_CONTINUE;
2186 Find_eval_ordering find_eval_ordering;
2188 // If S is a variable declaration, then ordinary traversal won't do
2189 // anything. We want to explicitly traverse the initialization
2190 // expression if there is one.
2191 Variable_declaration_statement* vds = s->variable_declaration_statement();
2192 Expression* init = NULL;
2193 Expression* orig_init = NULL;
2195 s->traverse_contents(&find_eval_ordering);
2198 init = vds->var()->var_value()->init();
2200 return TRAVERSE_CONTINUE;
2203 // It might seem that this could be
2204 // init->traverse_subexpressions. Unfortunately that can fail
2207 // newvar, err := call(arg())
2208 // Here newvar will have an init of call result 0 of
2209 // call(arg()). If we only traverse subexpressions, we will
2210 // only find arg(), and we won't bother to move anything out.
2211 // Then we get to the assignment to err, we will traverse the
2212 // whole statement, and this time we will find both call() and
2213 // arg(), and so we will move them out. This will cause them to
2214 // be put into temporary variables before the assignment to err
2215 // but after the declaration of newvar. To avoid that problem,
2216 // we traverse the entire expression here.
2217 Expression::traverse(&init, &find_eval_ordering);
2220 size_t c = find_eval_ordering.size();
2222 return TRAVERSE_CONTINUE;
2224 // If there is only one expression with a side-effect, we can
2225 // usually leave it in place. However, for an assignment statement,
2226 // we need to evaluate an expression on the right hand side before
2227 // we evaluate any index expression on the left hand side, so for
2228 // that case we always move the expression. Otherwise we mishandle
2229 // m[0] = len(m) where m is a map.
2230 if (c == 1 && s->classification() != Statement::STATEMENT_ASSIGNMENT)
2231 return TRAVERSE_CONTINUE;
2233 bool is_thunk = s->thunk_statement() != NULL;
2234 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2235 p != find_eval_ordering.end();
2238 Expression** pexpr = *p;
2240 // The last expression in a thunk will be the call passed to go
2241 // or defer, which we must not evaluate early.
2242 if (is_thunk && p + 1 == find_eval_ordering.end())
2245 Location loc = (*pexpr)->location();
2247 if ((*pexpr)->call_expression() == NULL
2248 || (*pexpr)->call_expression()->result_count() < 2)
2250 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2253 *pexpr = Expression::make_temporary_reference(ts, loc);
2257 // A call expression which returns multiple results needs to
2258 // be handled specially. We can't create a temporary
2259 // because there is no type to give it. Any actual uses of
2260 // the values will be done via Call_result_expressions.
2261 s = Statement::make_statement(*pexpr, true);
2264 block->insert_statement_before(*pindex, s);
2268 if (init != orig_init)
2269 vds->var()->var_value()->set_init(init);
2271 return TRAVERSE_CONTINUE;
2274 // Implement the order of evaluation rules for the initializer of a
2278 Order_eval::variable(Named_object* no)
2280 if (no->is_result_variable())
2281 return TRAVERSE_CONTINUE;
2282 Variable* var = no->var_value();
2283 Expression* init = var->init();
2284 if (!var->is_global() || init == NULL)
2285 return TRAVERSE_CONTINUE;
2287 Find_eval_ordering find_eval_ordering;
2288 Expression::traverse(&init, &find_eval_ordering);
2290 if (find_eval_ordering.size() <= 1)
2292 // If there is only one expression with a side-effect, we can
2293 // leave it in place.
2294 return TRAVERSE_SKIP_COMPONENTS;
2297 Expression* orig_init = init;
2299 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2300 p != find_eval_ordering.end();
2303 Expression** pexpr = *p;
2304 Location loc = (*pexpr)->location();
2306 if ((*pexpr)->call_expression() == NULL
2307 || (*pexpr)->call_expression()->result_count() < 2)
2309 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2312 *pexpr = Expression::make_temporary_reference(ts, loc);
2316 // A call expression which returns multiple results needs to
2317 // be handled specially.
2318 s = Statement::make_statement(*pexpr, true);
2320 var->add_preinit_statement(this->gogo_, s);
2323 if (init != orig_init)
2324 var->set_init(init);
2326 return TRAVERSE_SKIP_COMPONENTS;
2329 // Use temporary variables to implement the order of evaluation rules.
2332 Gogo::order_evaluations()
2334 Order_eval order_eval(this);
2335 this->traverse(&order_eval);
2338 // Traversal to convert calls to the predeclared recover function to
2339 // pass in an argument indicating whether it can recover from a panic
2342 class Convert_recover : public Traverse
2345 Convert_recover(Named_object* arg)
2346 : Traverse(traverse_expressions),
2352 expression(Expression**);
2355 // The argument to pass to the function.
2359 // Convert calls to recover.
2362 Convert_recover::expression(Expression** pp)
2364 Call_expression* ce = (*pp)->call_expression();
2365 if (ce != NULL && ce->is_recover_call())
2366 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2368 return TRAVERSE_CONTINUE;
2371 // Traversal for build_recover_thunks.
2373 class Build_recover_thunks : public Traverse
2376 Build_recover_thunks(Gogo* gogo)
2377 : Traverse(traverse_functions),
2382 function(Named_object*);
2386 can_recover_arg(Location);
2392 // If this function calls recover, turn it into a thunk.
2395 Build_recover_thunks::function(Named_object* orig_no)
2397 Function* orig_func = orig_no->func_value();
2398 if (!orig_func->calls_recover()
2399 || orig_func->is_recover_thunk()
2400 || orig_func->has_recover_thunk())
2401 return TRAVERSE_CONTINUE;
2403 Gogo* gogo = this->gogo_;
2404 Location location = orig_func->location();
2409 Function_type* orig_fntype = orig_func->type();
2410 Typed_identifier_list* new_params = new Typed_identifier_list();
2411 std::string receiver_name;
2412 if (orig_fntype->is_method())
2414 const Typed_identifier* receiver = orig_fntype->receiver();
2415 snprintf(buf, sizeof buf, "rt.%u", count);
2417 receiver_name = buf;
2418 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2419 receiver->location()));
2421 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2422 if (orig_params != NULL && !orig_params->empty())
2424 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2425 p != orig_params->end();
2428 snprintf(buf, sizeof buf, "pt.%u", count);
2430 new_params->push_back(Typed_identifier(buf, p->type(),
2434 snprintf(buf, sizeof buf, "pr.%u", count);
2436 std::string can_recover_name = buf;
2437 new_params->push_back(Typed_identifier(can_recover_name,
2438 Type::lookup_bool_type(),
2439 orig_fntype->location()));
2441 const Typed_identifier_list* orig_results = orig_fntype->results();
2442 Typed_identifier_list* new_results;
2443 if (orig_results == NULL || orig_results->empty())
2447 new_results = new Typed_identifier_list();
2448 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2449 p != orig_results->end();
2451 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2454 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2456 orig_fntype->location());
2457 if (orig_fntype->is_varargs())
2458 new_fntype->set_is_varargs();
2460 std::string name = orig_no->name() + "$recover";
2461 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2463 Function *new_func = new_no->func_value();
2464 if (orig_func->enclosing() != NULL)
2465 new_func->set_enclosing(orig_func->enclosing());
2467 // We build the code for the original function attached to the new
2468 // function, and then swap the original and new function bodies.
2469 // This means that existing references to the original function will
2470 // then refer to the new function. That makes this code a little
2471 // confusing, in that the reference to NEW_NO really refers to the
2472 // other function, not the one we are building.
2474 Expression* closure = NULL;
2475 if (orig_func->needs_closure())
2477 Named_object* orig_closure_no = orig_func->closure_var();
2478 Variable* orig_closure_var = orig_closure_no->var_value();
2479 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2480 true, false, location);
2481 snprintf(buf, sizeof buf, "closure.%u", count);
2483 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2485 new_func->set_closure_var(new_closure_no);
2486 closure = Expression::make_var_reference(new_closure_no, location);
2489 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2491 Expression_list* args = new Expression_list();
2492 if (new_params != NULL)
2494 // Note that we skip the last parameter, which is the boolean
2495 // indicating whether recover can succed.
2496 for (Typed_identifier_list::const_iterator p = new_params->begin();
2497 p + 1 != new_params->end();
2500 Named_object* p_no = gogo->lookup(p->name(), NULL);
2501 go_assert(p_no != NULL
2502 && p_no->is_variable()
2503 && p_no->var_value()->is_parameter());
2504 args->push_back(Expression::make_var_reference(p_no, location));
2507 args->push_back(this->can_recover_arg(location));
2509 gogo->start_block(location);
2511 Call_expression* call = Expression::make_call(fn, args, false, location);
2513 // Any varargs call has already been lowered.
2514 call->set_varargs_are_lowered();
2517 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2518 s = Statement::make_statement(call, true);
2521 Expression_list* vals = new Expression_list();
2522 size_t rc = orig_fntype->results()->size();
2524 vals->push_back(call);
2527 for (size_t i = 0; i < rc; ++i)
2528 vals->push_back(Expression::make_call_result(call, i));
2530 s = Statement::make_return_statement(vals, location);
2532 s->determine_types();
2533 gogo->add_statement(s);
2535 Block* b = gogo->finish_block(location);
2537 gogo->add_block(b, location);
2539 // Lower the call in case it returns multiple results.
2540 gogo->lower_block(new_no, b);
2542 gogo->finish_function(location);
2544 // Swap the function bodies and types.
2545 new_func->swap_for_recover(orig_func);
2546 orig_func->set_is_recover_thunk();
2547 new_func->set_calls_recover();
2548 new_func->set_has_recover_thunk();
2550 Bindings* orig_bindings = orig_func->block()->bindings();
2551 Bindings* new_bindings = new_func->block()->bindings();
2552 if (orig_fntype->is_method())
2554 // We changed the receiver to be a regular parameter. We have
2555 // to update the binding accordingly in both functions.
2556 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2557 go_assert(orig_rec_no != NULL
2558 && orig_rec_no->is_variable()
2559 && !orig_rec_no->var_value()->is_receiver());
2560 orig_rec_no->var_value()->set_is_receiver();
2562 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2563 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2564 if (new_rec_no == NULL)
2565 go_assert(saw_errors());
2568 go_assert(new_rec_no->is_variable()
2569 && new_rec_no->var_value()->is_receiver());
2570 new_rec_no->var_value()->set_is_not_receiver();
2574 // Because we flipped blocks but not types, the can_recover
2575 // parameter appears in the (now) old bindings as a parameter.
2576 // Change it to a local variable, whereupon it will be discarded.
2577 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2578 go_assert(can_recover_no != NULL
2579 && can_recover_no->is_variable()
2580 && can_recover_no->var_value()->is_parameter());
2581 orig_bindings->remove_binding(can_recover_no);
2583 // Add the can_recover argument to the (now) new bindings, and
2584 // attach it to any recover statements.
2585 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2586 false, true, false, location);
2587 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2589 Convert_recover convert_recover(can_recover_no);
2590 new_func->traverse(&convert_recover);
2592 // Update the function pointers in any named results.
2593 new_func->update_result_variables();
2594 orig_func->update_result_variables();
2596 return TRAVERSE_CONTINUE;
2599 // Return the expression to pass for the .can_recover parameter to the
2600 // new function. This indicates whether a call to recover may return
2601 // non-nil. The expression is
2602 // __go_can_recover(__builtin_return_address()).
2605 Build_recover_thunks::can_recover_arg(Location location)
2607 static Named_object* builtin_return_address;
2608 if (builtin_return_address == NULL)
2610 const Location bloc = Linemap::predeclared_location();
2612 Typed_identifier_list* param_types = new Typed_identifier_list();
2613 Type* uint_type = Type::lookup_integer_type("uint");
2614 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2616 Typed_identifier_list* return_types = new Typed_identifier_list();
2617 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2618 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2620 Function_type* fntype = Type::make_function_type(NULL, param_types,
2621 return_types, bloc);
2622 builtin_return_address =
2623 Named_object::make_function_declaration("__builtin_return_address",
2624 NULL, fntype, bloc);
2625 const char* n = "__builtin_return_address";
2626 builtin_return_address->func_declaration_value()->set_asm_name(n);
2629 static Named_object* can_recover;
2630 if (can_recover == NULL)
2632 const Location bloc = Linemap::predeclared_location();
2633 Typed_identifier_list* param_types = new Typed_identifier_list();
2634 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2635 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2636 Type* boolean_type = Type::lookup_bool_type();
2637 Typed_identifier_list* results = new Typed_identifier_list();
2638 results->push_back(Typed_identifier("", boolean_type, bloc));
2639 Function_type* fntype = Type::make_function_type(NULL, param_types,
2641 can_recover = Named_object::make_function_declaration("__go_can_recover",
2644 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2647 Expression* fn = Expression::make_func_reference(builtin_return_address,
2651 mpz_init_set_ui(zval, 0UL);
2652 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2654 Expression_list *args = new Expression_list();
2655 args->push_back(zexpr);
2657 Expression* call = Expression::make_call(fn, args, false, location);
2659 args = new Expression_list();
2660 args->push_back(call);
2662 fn = Expression::make_func_reference(can_recover, NULL, location);
2663 return Expression::make_call(fn, args, false, location);
2666 // Build thunks for functions which call recover. We build a new
2667 // function with an extra parameter, which is whether a call to
2668 // recover can succeed. We then move the body of this function to
2669 // that one. We then turn this function into a thunk which calls the
2670 // new one, passing the value of
2671 // __go_can_recover(__builtin_return_address()). The function will be
2672 // marked as not splitting the stack. This will cooperate with the
2673 // implementation of defer to make recover do the right thing.
2676 Gogo::build_recover_thunks()
2678 Build_recover_thunks build_recover_thunks(this);
2679 this->traverse(&build_recover_thunks);
2682 // Look for named types to see whether we need to create an interface
2685 class Build_method_tables : public Traverse
2688 Build_method_tables(Gogo* gogo,
2689 const std::vector<Interface_type*>& interfaces)
2690 : Traverse(traverse_types),
2691 gogo_(gogo), interfaces_(interfaces)
2700 // A list of locally defined interfaces which have hidden methods.
2701 const std::vector<Interface_type*>& interfaces_;
2704 // Build all required interface method tables for types. We need to
2705 // ensure that we have an interface method table for every interface
2706 // which has a hidden method, for every named type which implements
2707 // that interface. Normally we can just build interface method tables
2708 // as we need them. However, in some cases we can require an
2709 // interface method table for an interface defined in a different
2710 // package for a type defined in that package. If that interface and
2711 // type both use a hidden method, that is OK. However, we will not be
2712 // able to build that interface method table when we need it, because
2713 // the type's hidden method will be static. So we have to build it
2714 // here, and just refer it from other packages as needed.
2717 Gogo::build_interface_method_tables()
2722 std::vector<Interface_type*> hidden_interfaces;
2723 hidden_interfaces.reserve(this->interface_types_.size());
2724 for (std::vector<Interface_type*>::const_iterator pi =
2725 this->interface_types_.begin();
2726 pi != this->interface_types_.end();
2729 const Typed_identifier_list* methods = (*pi)->methods();
2730 if (methods == NULL)
2732 for (Typed_identifier_list::const_iterator pm = methods->begin();
2733 pm != methods->end();
2736 if (Gogo::is_hidden_name(pm->name()))
2738 hidden_interfaces.push_back(*pi);
2744 if (!hidden_interfaces.empty())
2746 // Now traverse the tree looking for all named types.
2747 Build_method_tables bmt(this, hidden_interfaces);
2748 this->traverse(&bmt);
2751 // We no longer need the list of interfaces.
2753 this->interface_types_.clear();
2756 // This is called for each type. For a named type, for each of the
2757 // interfaces with hidden methods that it implements, create the
2761 Build_method_tables::type(Type* type)
2763 Named_type* nt = type->named_type();
2766 for (std::vector<Interface_type*>::const_iterator p =
2767 this->interfaces_.begin();
2768 p != this->interfaces_.end();
2771 // We ask whether a pointer to the named type implements the
2772 // interface, because a pointer can implement more methods
2774 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2776 nt->interface_method_table(this->gogo_, *p, false);
2777 nt->interface_method_table(this->gogo_, *p, true);
2781 return TRAVERSE_CONTINUE;
2784 // Traversal class used to check for return statements.
2786 class Check_return_statements_traverse : public Traverse
2789 Check_return_statements_traverse()
2790 : Traverse(traverse_functions)
2794 function(Named_object*);
2797 // Check that a function has a return statement if it needs one.
2800 Check_return_statements_traverse::function(Named_object* no)
2802 Function* func = no->func_value();
2803 const Function_type* fntype = func->type();
2804 const Typed_identifier_list* results = fntype->results();
2806 // We only need a return statement if there is a return value.
2807 if (results == NULL || results->empty())
2808 return TRAVERSE_CONTINUE;
2810 if (func->block()->may_fall_through())
2811 error_at(func->location(), "control reaches end of non-void function");
2813 return TRAVERSE_CONTINUE;
2816 // Check return statements.
2819 Gogo::check_return_statements()
2821 Check_return_statements_traverse traverse;
2822 this->traverse(&traverse);
2825 // Get the unique prefix to use before all exported symbols. This
2826 // must be unique across the entire link.
2829 Gogo::unique_prefix() const
2831 go_assert(!this->unique_prefix_.empty());
2832 return this->unique_prefix_;
2835 // Set the unique prefix to use before all exported symbols. This
2836 // comes from the command line option -fgo-prefix=XXX.
2839 Gogo::set_unique_prefix(const std::string& arg)
2841 go_assert(this->unique_prefix_.empty());
2842 this->unique_prefix_ = arg;
2843 this->unique_prefix_specified_ = true;
2846 // Work out the package priority. It is one more than the maximum
2847 // priority of an imported package.
2850 Gogo::package_priority() const
2853 for (Packages::const_iterator p = this->packages_.begin();
2854 p != this->packages_.end();
2856 if (p->second->priority() > priority)
2857 priority = p->second->priority();
2858 return priority + 1;
2861 // Export identifiers as requested.
2866 // For now we always stream to a section. Later we may want to
2867 // support streaming to a separate file.
2868 Stream_to_section stream;
2870 Export exp(&stream);
2871 exp.register_builtin_types(this);
2872 exp.export_globals(this->package_name(),
2873 this->unique_prefix(),
2874 this->package_priority(),
2876 (this->need_init_fn_ && !this->is_main_package()
2877 ? this->get_init_fn_name()
2879 this->imported_init_fns_,
2880 this->package_->bindings());
2883 // Find the blocks in order to convert named types defined in blocks.
2885 class Convert_named_types : public Traverse
2888 Convert_named_types(Gogo* gogo)
2889 : Traverse(traverse_blocks),
2895 block(Block* block);
2902 Convert_named_types::block(Block* block)
2904 this->gogo_->convert_named_types_in_bindings(block->bindings());
2905 return TRAVERSE_CONTINUE;
2908 // Convert all named types to the backend representation. Since named
2909 // types can refer to other types, this needs to be done in the right
2910 // sequence, which is handled by Named_type::convert. Here we arrange
2911 // to call that for each named type.
2914 Gogo::convert_named_types()
2916 this->convert_named_types_in_bindings(this->globals_);
2917 for (Packages::iterator p = this->packages_.begin();
2918 p != this->packages_.end();
2921 Package* package = p->second;
2922 this->convert_named_types_in_bindings(package->bindings());
2925 Convert_named_types cnt(this);
2926 this->traverse(&cnt);
2928 // Make all the builtin named types used for type descriptors, and
2929 // then convert them. They will only be written out if they are
2931 Type::make_type_descriptor_type();
2932 Type::make_type_descriptor_ptr_type();
2933 Function_type::make_function_type_descriptor_type();
2934 Pointer_type::make_pointer_type_descriptor_type();
2935 Struct_type::make_struct_type_descriptor_type();
2936 Array_type::make_array_type_descriptor_type();
2937 Array_type::make_slice_type_descriptor_type();
2938 Map_type::make_map_type_descriptor_type();
2939 Map_type::make_map_descriptor_type();
2940 Channel_type::make_chan_type_descriptor_type();
2941 Interface_type::make_interface_type_descriptor_type();
2942 Type::convert_builtin_named_types(this);
2944 Runtime::convert_types(this);
2946 this->named_types_are_converted_ = true;
2949 // Convert all names types in a set of bindings.
2952 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2954 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2955 p != bindings->end_definitions();
2958 if ((*p)->is_type())
2959 (*p)->type_value()->convert(this);
2965 Function::Function(Function_type* type, Function* enclosing, Block* block,
2967 : type_(type), enclosing_(enclosing), results_(NULL),
2968 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2969 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2970 is_recover_thunk_(false), has_recover_thunk_(false)
2974 // Create the named result variables.
2977 Function::create_result_variables(Gogo* gogo)
2979 const Typed_identifier_list* results = this->type_->results();
2980 if (results == NULL || results->empty())
2983 if (!results->front().name().empty())
2984 this->results_are_named_ = true;
2986 this->results_ = new Results();
2987 this->results_->reserve(results->size());
2989 Block* block = this->block_;
2991 for (Typed_identifier_list::const_iterator p = results->begin();
2992 p != results->end();
2995 std::string name = p->name();
2996 if (name.empty() || Gogo::is_sink_name(name))
2998 static int result_counter;
3000 snprintf(buf, sizeof buf, "$ret%d", result_counter);
3002 name = gogo->pack_hidden_name(buf, false);
3004 Result_variable* result = new Result_variable(p->type(), this, index,
3006 Named_object* no = block->bindings()->add_result_variable(name, result);
3007 if (no->is_result_variable())
3008 this->results_->push_back(no);
3011 static int dummy_result_count;
3013 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
3014 ++dummy_result_count;
3015 name = gogo->pack_hidden_name(buf, false);
3016 no = block->bindings()->add_result_variable(name, result);
3017 go_assert(no->is_result_variable());
3018 this->results_->push_back(no);
3023 // Update the named result variables when cloning a function which
3027 Function::update_result_variables()
3029 if (this->results_ == NULL)
3032 for (Results::iterator p = this->results_->begin();
3033 p != this->results_->end();
3035 (*p)->result_var_value()->set_function(this);
3038 // Return the closure variable, creating it if necessary.
3041 Function::closure_var()
3043 if (this->closure_var_ == NULL)
3045 // We don't know the type of the variable yet. We add fields as
3047 Location loc = this->type_->location();
3048 Struct_field_list* sfl = new Struct_field_list;
3049 Type* struct_type = Type::make_struct_type(sfl, loc);
3050 Variable* var = new Variable(Type::make_pointer_type(struct_type),
3051 NULL, false, true, false, loc);
3053 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
3054 // Note that the new variable is not in any binding contour.
3056 return this->closure_var_;
3059 // Set the type of the closure variable.
3062 Function::set_closure_type()
3064 if (this->closure_var_ == NULL)
3066 Named_object* closure = this->closure_var_;
3067 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3068 unsigned int index = 0;
3069 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3070 p != this->closure_fields_.end();
3073 Named_object* no = p->first;
3075 snprintf(buf, sizeof buf, "%u", index);
3076 std::string n = no->name() + buf;
3078 if (no->is_variable())
3079 var_type = no->var_value()->type();
3081 var_type = no->result_var_value()->type();
3082 Type* field_type = Type::make_pointer_type(var_type);
3083 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3087 // Return whether this function is a method.
3090 Function::is_method() const
3092 return this->type_->is_method();
3095 // Add a label definition.
3098 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3101 Label* lnull = NULL;
3102 std::pair<Labels::iterator, bool> ins =
3103 this->labels_.insert(std::make_pair(label_name, lnull));
3107 // This is a new label.
3108 label = new Label(label_name);
3109 ins.first->second = label;
3113 // The label was already in the hash table.
3114 label = ins.first->second;
3115 if (label->is_defined())
3117 error_at(location, "label %qs already defined",
3118 Gogo::message_name(label_name).c_str());
3119 inform(label->location(), "previous definition of %qs was here",
3120 Gogo::message_name(label_name).c_str());
3121 return new Label(label_name);
3125 label->define(location, gogo->bindings_snapshot(location));
3127 // Issue any errors appropriate for any previous goto's to this
3129 const std::vector<Bindings_snapshot*>& refs(label->refs());
3130 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3133 (*p)->check_goto_to(gogo->current_block());
3134 label->clear_refs();
3139 // Add a reference to a label.
3142 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3143 Location location, bool issue_goto_errors)
3145 Label* lnull = NULL;
3146 std::pair<Labels::iterator, bool> ins =
3147 this->labels_.insert(std::make_pair(label_name, lnull));
3151 // The label was already in the hash table.
3152 label = ins.first->second;
3156 go_assert(ins.first->second == NULL);
3157 label = new Label(label_name);
3158 ins.first->second = label;
3161 label->set_is_used();
3163 if (issue_goto_errors)
3165 Bindings_snapshot* snapshot = label->snapshot();
3166 if (snapshot != NULL)
3167 snapshot->check_goto_from(gogo->current_block(), location);
3169 label->add_snapshot_ref(gogo->bindings_snapshot(location));
3175 // Warn about labels that are defined but not used.
3178 Function::check_labels() const
3180 for (Labels::const_iterator p = this->labels_.begin();
3181 p != this->labels_.end();
3184 Label* label = p->second;
3185 if (!label->is_used())
3186 error_at(label->location(), "label %qs defined and not used",
3187 Gogo::message_name(label->name()).c_str());
3191 // Swap one function with another. This is used when building the
3192 // thunk we use to call a function which calls recover. It may not
3193 // work for any other case.
3196 Function::swap_for_recover(Function *x)
3198 go_assert(this->enclosing_ == x->enclosing_);
3199 std::swap(this->results_, x->results_);
3200 std::swap(this->closure_var_, x->closure_var_);
3201 std::swap(this->block_, x->block_);
3202 go_assert(this->location_ == x->location_);
3203 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3204 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3207 // Traverse the tree.
3210 Function::traverse(Traverse* traverse)
3212 unsigned int traverse_mask = traverse->traverse_mask();
3215 & (Traverse::traverse_types | Traverse::traverse_expressions))
3218 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3219 return TRAVERSE_EXIT;
3222 // FIXME: We should check traverse_functions here if nested
3223 // functions are stored in block bindings.
3224 if (this->block_ != NULL
3226 & (Traverse::traverse_variables
3227 | Traverse::traverse_constants
3228 | Traverse::traverse_blocks
3229 | Traverse::traverse_statements
3230 | Traverse::traverse_expressions
3231 | Traverse::traverse_types)) != 0)
3233 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3234 return TRAVERSE_EXIT;
3237 return TRAVERSE_CONTINUE;
3240 // Work out types for unspecified variables and constants.
3243 Function::determine_types()
3245 if (this->block_ != NULL)
3246 this->block_->determine_types();
3249 // Get a pointer to the variable representing the defer stack for this
3250 // function, making it if necessary. The value of the variable is set
3251 // by the runtime routines to true if the function is returning,
3252 // rather than panicing through. A pointer to this variable is used
3253 // as a marker for the functions on the defer stack associated with
3254 // this function. A function-specific variable permits inlining a
3255 // function which uses defer.
3258 Function::defer_stack(Location location)
3260 if (this->defer_stack_ == NULL)
3262 Type* t = Type::lookup_bool_type();
3263 Expression* n = Expression::make_boolean(false, location);
3264 this->defer_stack_ = Statement::make_temporary(t, n, location);
3265 this->defer_stack_->set_is_address_taken();
3267 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3269 return Expression::make_unary(OPERATOR_AND, ref, location);
3272 // Export the function.
3275 Function::export_func(Export* exp, const std::string& name) const
3277 Function::export_func_with_type(exp, name, this->type_);
3280 // Export a function with a type.
3283 Function::export_func_with_type(Export* exp, const std::string& name,
3284 const Function_type* fntype)
3286 exp->write_c_string("func ");
3288 if (fntype->is_method())
3290 exp->write_c_string("(");
3291 const Typed_identifier* receiver = fntype->receiver();
3292 exp->write_name(receiver->name());
3293 exp->write_c_string(" ");
3294 exp->write_type(receiver->type());
3295 exp->write_c_string(") ");
3298 exp->write_string(name);
3300 exp->write_c_string(" (");
3301 const Typed_identifier_list* parameters = fntype->parameters();
3302 if (parameters != NULL)
3304 bool is_varargs = fntype->is_varargs();
3306 for (Typed_identifier_list::const_iterator p = parameters->begin();
3307 p != parameters->end();
3313 exp->write_c_string(", ");
3314 exp->write_name(p->name());
3315 exp->write_c_string(" ");
3316 if (!is_varargs || p + 1 != parameters->end())
3317 exp->write_type(p->type());
3320 exp->write_c_string("...");
3321 exp->write_type(p->type()->array_type()->element_type());
3325 exp->write_c_string(")");
3327 const Typed_identifier_list* results = fntype->results();
3328 if (results != NULL)
3330 if (results->size() == 1 && results->begin()->name().empty())
3332 exp->write_c_string(" ");
3333 exp->write_type(results->begin()->type());
3337 exp->write_c_string(" (");
3339 for (Typed_identifier_list::const_iterator p = results->begin();
3340 p != results->end();
3346 exp->write_c_string(", ");
3347 exp->write_name(p->name());
3348 exp->write_c_string(" ");
3349 exp->write_type(p->type());
3351 exp->write_c_string(")");
3354 exp->write_c_string(";\n");
3357 // Import a function.
3360 Function::import_func(Import* imp, std::string* pname,
3361 Typed_identifier** preceiver,
3362 Typed_identifier_list** pparameters,
3363 Typed_identifier_list** presults,
3366 imp->require_c_string("func ");
3369 if (imp->peek_char() == '(')
3371 imp->require_c_string("(");
3372 std::string name = imp->read_name();
3373 imp->require_c_string(" ");
3374 Type* rtype = imp->read_type();
3375 *preceiver = new Typed_identifier(name, rtype, imp->location());
3376 imp->require_c_string(") ");
3379 *pname = imp->read_identifier();
3381 Typed_identifier_list* parameters;
3382 *is_varargs = false;
3383 imp->require_c_string(" (");
3384 if (imp->peek_char() == ')')
3388 parameters = new Typed_identifier_list();
3391 std::string name = imp->read_name();
3392 imp->require_c_string(" ");
3394 if (imp->match_c_string("..."))
3400 Type* ptype = imp->read_type();
3402 ptype = Type::make_array_type(ptype, NULL);
3403 parameters->push_back(Typed_identifier(name, ptype,
3405 if (imp->peek_char() != ',')
3407 go_assert(!*is_varargs);
3408 imp->require_c_string(", ");
3411 imp->require_c_string(")");
3412 *pparameters = parameters;
3414 Typed_identifier_list* results;
3415 if (imp->peek_char() != ' ')
3419 results = new Typed_identifier_list();
3420 imp->require_c_string(" ");
3421 if (imp->peek_char() != '(')
3423 Type* rtype = imp->read_type();
3424 results->push_back(Typed_identifier("", rtype, imp->location()));
3428 imp->require_c_string("(");
3431 std::string name = imp->read_name();
3432 imp->require_c_string(" ");
3433 Type* rtype = imp->read_type();
3434 results->push_back(Typed_identifier(name, rtype,
3436 if (imp->peek_char() != ',')
3438 imp->require_c_string(", ");
3440 imp->require_c_string(")");
3443 imp->require_c_string(";\n");
3444 *presults = results;
3449 Block::Block(Block* enclosing, Location location)
3450 : enclosing_(enclosing), statements_(),
3451 bindings_(new Bindings(enclosing == NULL
3453 : enclosing->bindings())),
3454 start_location_(location),
3455 end_location_(UNKNOWN_LOCATION)
3459 // Add a statement to a block.
3462 Block::add_statement(Statement* statement)
3464 this->statements_.push_back(statement);
3467 // Add a statement to the front of a block. This is slow but is only
3468 // used for reference counts of parameters.
3471 Block::add_statement_at_front(Statement* statement)
3473 this->statements_.insert(this->statements_.begin(), statement);
3476 // Replace a statement in a block.
3479 Block::replace_statement(size_t index, Statement* s)
3481 go_assert(index < this->statements_.size());
3482 this->statements_[index] = s;
3485 // Add a statement before another statement.
3488 Block::insert_statement_before(size_t index, Statement* s)
3490 go_assert(index < this->statements_.size());
3491 this->statements_.insert(this->statements_.begin() + index, s);
3494 // Add a statement after another statement.
3497 Block::insert_statement_after(size_t index, Statement* s)
3499 go_assert(index < this->statements_.size());
3500 this->statements_.insert(this->statements_.begin() + index + 1, s);
3503 // Traverse the tree.
3506 Block::traverse(Traverse* traverse)
3508 unsigned int traverse_mask = traverse->traverse_mask();
3510 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3512 int t = traverse->block(this);
3513 if (t == TRAVERSE_EXIT)
3514 return TRAVERSE_EXIT;
3515 else if (t == TRAVERSE_SKIP_COMPONENTS)
3516 return TRAVERSE_CONTINUE;
3520 & (Traverse::traverse_variables
3521 | Traverse::traverse_constants
3522 | Traverse::traverse_expressions
3523 | Traverse::traverse_types)) != 0)
3525 const unsigned int e_or_t = (Traverse::traverse_expressions
3526 | Traverse::traverse_types);
3527 const unsigned int e_or_t_or_s = (e_or_t
3528 | Traverse::traverse_statements);
3529 for (Bindings::const_definitions_iterator pb =
3530 this->bindings_->begin_definitions();
3531 pb != this->bindings_->end_definitions();
3534 int t = TRAVERSE_CONTINUE;
3535 switch ((*pb)->classification())
3537 case Named_object::NAMED_OBJECT_CONST: